openai_api_completions.ipynb 11.5 KB
Newer Older
Chayenne's avatar
Chayenne committed
1
2
3
4
5
6
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
Lianmin Zheng's avatar
Lianmin Zheng committed
7
    "# OpenAI APIs - Completions\n",
Chayenne's avatar
Chayenne committed
8
    "\n",
9
10
    "SGLang provides OpenAI-compatible APIs to enable a smooth transition from OpenAI services to self-hosted local models.\n",
    "A complete reference for the API is available in the [OpenAI API Reference](https://platform.openai.com/docs/api-reference).\n",
11
    "\n",
12
    "This tutorial covers the following popular APIs:\n",
Chayenne's avatar
Chayenne committed
13
14
15
    "\n",
    "- `chat/completions`\n",
    "- `completions`\n",
16
    "\n",
simveit's avatar
simveit committed
17
    "Check out other tutorials to learn about [vision APIs](https://docs.sglang.ai/backend/openai_api_vision.html) for vision-language models and [embedding APIs](https://docs.sglang.ai/backend/openai_api_embeddings.html) for embedding models."
Chayenne's avatar
Chayenne committed
18
19
20
21
22
23
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
24
    "## Launch A Server\n",
Chayenne's avatar
Chayenne committed
25
    "\n",
26
    "Launch the server in your terminal and wait for it to initialize."
Chayenne's avatar
Chayenne committed
27
28
29
30
   ]
  },
  {
   "cell_type": "code",
Chayenne's avatar
Chayenne committed
31
   "execution_count": null,
32
   "metadata": {},
Chayenne's avatar
Chayenne committed
33
   "outputs": [],
Chayenne's avatar
Chayenne committed
34
   "source": [
35
36
37
38
39
40
41
42
43
    "from sglang.test.test_utils import is_in_ci\n",
    "\n",
    "if is_in_ci():\n",
    "    from patch import launch_server_cmd\n",
    "else:\n",
    "    from sglang.utils import launch_server_cmd\n",
    "\n",
    "from sglang.utils import wait_for_server, print_highlight, terminate_process\n",
    "\n",
Chayenne's avatar
Chayenne committed
44
    "\n",
45
    "server_process, port = launch_server_cmd(\n",
46
    "    \"python3 -m sglang.launch_server --model-path qwen/qwen2.5-0.5b-instruct --host 0.0.0.0 --mem-fraction-static 0.8\"\n",
Chayenne's avatar
Chayenne committed
47
48
    ")\n",
    "\n",
49
50
    "wait_for_server(f\"http://localhost:{port}\")\n",
    "print(f\"Server started on http://localhost:{port}\")"
Chayenne's avatar
Chayenne committed
51
52
   ]
  },
53
54
55
56
57
58
59
60
61
62
63
64
65
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Chat Completions\n",
    "\n",
    "### Usage\n",
    "\n",
    "The server fully implements the OpenAI API.\n",
    "It will automatically apply the chat template specified in the Hugging Face tokenizer, if one is available.\n",
    "You can also specify a custom chat template with `--chat-template` when launching the server."
   ]
  },
Chayenne's avatar
Chayenne committed
66
67
  {
   "cell_type": "code",
Chayenne's avatar
Chayenne committed
68
   "execution_count": null,
69
   "metadata": {},
Chayenne's avatar
Chayenne committed
70
   "outputs": [],
Chayenne's avatar
Chayenne committed
71
72
73
   "source": [
    "import openai\n",
    "\n",
74
    "client = openai.Client(base_url=f\"http://127.0.0.1:{port}/v1\", api_key=\"None\")\n",
Chayenne's avatar
Chayenne committed
75
76
    "\n",
    "response = client.chat.completions.create(\n",
77
    "    model=\"qwen/qwen2.5-0.5b-instruct\",\n",
Chayenne's avatar
Chayenne committed
78
79
80
81
82
83
    "    messages=[\n",
    "        {\"role\": \"user\", \"content\": \"List 3 countries and their capitals.\"},\n",
    "    ],\n",
    "    temperature=0,\n",
    "    max_tokens=64,\n",
    ")\n",
84
85
    "\n",
    "print_highlight(f\"Response: {response}\")"
Chayenne's avatar
Chayenne committed
86
87
88
89
90
91
92
93
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Parameters\n",
    "\n",
94
    "The chat completions API accepts OpenAI Chat Completions API's parameters. Refer to [OpenAI Chat Completions API](https://platform.openai.com/docs/api-reference/chat/create) for more details.\n",
Chayenne's avatar
Chayenne committed
95
    "\n",
96
97
98
99
    "SGLang extends the standard API with the `extra_body` parameter, allowing for additional customization. One key option within `extra_body` is `chat_template_kwargs`, which can be used to pass arguments to the chat template processor.\n",
    "\n",
    "#### Enabling Model Thinking/Reasoning\n",
    "\n",
100
101
102
103
104
105
106
    "You can use `chat_template_kwargs` to enable or disable the model's internal thinking or reasoning process output. Set `\"enable_thinking\": True` within `chat_template_kwargs` to include the reasoning steps in the response. This requires launching the server with a compatible reasoning parser.\n",
    "\n",
    "**Reasoning Parser Options:**\n",
    "- `--reasoning-parser deepseek-r1`: For DeepSeek-R1 family models (R1, R1-0528, R1-Distill)\n",
    "- `--reasoning-parser qwen3`: For standard Qwen3 models that support `enable_thinking` parameter\n",
    "- `--reasoning-parser qwen3-thinking`: For Qwen3-Thinking models (e.g., Qwen/Qwen3-235B-A22B-Thinking-2507) that always generate thinking content\n",
    "- `--reasoning-parser kimi`: For Kimi thinking models\n",
107
108
109
110
    "\n",
    "Here's an example demonstrating how to enable thinking and retrieve the reasoning content separately (using `separate_reasoning: True`):\n",
    "\n",
    "```python\n",
111
    "# For standard Qwen3 models with enable_thinking support:\n",
112
113
    "# python3 -m sglang.launch_server --model-path QwQ/Qwen3-32B-250415 --reasoning-parser qwen3 ...\n",
    "\n",
114
115
116
    "# For Qwen3-Thinking models that always think:\n",
    "# python3 -m sglang.launch_server --model-path Qwen/Qwen3-235B-A22B-Thinking-2507 --reasoning-parser qwen3-thinking ...\n",
    "\n",
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
    "from openai import OpenAI\n",
    "\n",
    "# Modify OpenAI's API key and API base to use SGLang's API server.\n",
    "openai_api_key = \"EMPTY\"\n",
    "openai_api_base = f\"http://127.0.0.1:{port}/v1\" # Use the correct port\n",
    "\n",
    "client = OpenAI(\n",
    "    api_key=openai_api_key,\n",
    "    base_url=openai_api_base,\n",
    ")\n",
    "\n",
    "model = \"QwQ/Qwen3-32B-250415\" # Use the model loaded by the server\n",
    "messages = [{\"role\": \"user\", \"content\": \"9.11 and 9.8, which is greater?\"}]\n",
    "\n",
    "response = client.chat.completions.create(\n",
    "    model=model,\n",
    "    messages=messages,\n",
    "    extra_body={\n",
135
    "        \"chat_template_kwargs\": {\"enable_thinking\": True}, # Only for standard Qwen3 models\n",
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
    "        \"separate_reasoning\": True\n",
    "    }\n",
    ")\n",
    "\n",
    "print(\"response.choices[0].message.reasoning_content: \\n\", response.choices[0].message.reasoning_content)\n",
    "print(\"response.choices[0].message.content: \\n\", response.choices[0].message.content)\n",
    "```\n",
    "\n",
    "**Example Output:**\n",
    "\n",
    "```\n",
    "response.choices[0].message.reasoning_content: \n",
    " Okay, so I need to figure out which number is greater between 9.11 and 9.8. Hmm, let me think. Both numbers start with 9, right? So the whole number part is the same. That means I need to look at the decimal parts to determine which one is bigger.\n",
    "...\n",
    "Therefore, after checking multiple methods—aligning decimals, subtracting, converting to fractions, and using a real-world analogy—it's clear that 9.8 is greater than 9.11.\n",
    "\n",
    "response.choices[0].message.content: \n",
    " To determine which number is greater between **9.11** and **9.8**, follow these steps:\n",
    "...\n",
    "**Answer**:  \n",
    "9.8 is greater than 9.11.\n",
    "```\n",
    "\n",
    "Setting `\"enable_thinking\": False` (or omitting it) will result in `reasoning_content` being `None`.\n",
    "\n",
161
162
    "**Note for Qwen3-Thinking models:** These models always generate thinking content and do not support the `enable_thinking` parameter. When using `--reasoning-parser qwen3-thinking`, the model will always produce reasoning content regardless of the `enable_thinking` setting.\n",
    "\n",
163
    "Here is an example of a detailed chat completion request using standard OpenAI parameters:"
Chayenne's avatar
Chayenne committed
164
165
166
167
   ]
  },
  {
   "cell_type": "code",
Chayenne's avatar
Chayenne committed
168
   "execution_count": null,
169
   "metadata": {},
Chayenne's avatar
Chayenne committed
170
   "outputs": [],
Chayenne's avatar
Chayenne committed
171
172
   "source": [
    "response = client.chat.completions.create(\n",
173
    "    model=\"qwen/qwen2.5-0.5b-instruct\",\n",
Chayenne's avatar
Chayenne committed
174
175
176
177
178
179
180
181
182
183
184
185
186
    "    messages=[\n",
    "        {\n",
    "            \"role\": \"system\",\n",
    "            \"content\": \"You are a knowledgeable historian who provides concise responses.\",\n",
    "        },\n",
    "        {\"role\": \"user\", \"content\": \"Tell me about ancient Rome\"},\n",
    "        {\n",
    "            \"role\": \"assistant\",\n",
    "            \"content\": \"Ancient Rome was a civilization centered in Italy.\",\n",
    "        },\n",
    "        {\"role\": \"user\", \"content\": \"What were their major achievements?\"},\n",
    "    ],\n",
    "    temperature=0.3,  # Lower temperature for more focused responses\n",
Lianmin Zheng's avatar
Lianmin Zheng committed
187
    "    max_tokens=128,  # Reasonable length for a concise response\n",
Chayenne's avatar
Chayenne committed
188
189
190
191
192
193
194
    "    top_p=0.95,  # Slightly higher for better fluency\n",
    "    presence_penalty=0.2,  # Mild penalty to avoid repetition\n",
    "    frequency_penalty=0.2,  # Mild penalty for more natural language\n",
    "    n=1,  # Single response is usually more stable\n",
    "    seed=42,  # Keep for reproducibility\n",
    ")\n",
    "\n",
Lianmin Zheng's avatar
Lianmin Zheng committed
195
196
197
198
199
200
201
    "print_highlight(response.choices[0].message.content)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
Chayenne's avatar
Chayenne committed
202
    "Streaming mode is also supported."
Lianmin Zheng's avatar
Lianmin Zheng committed
203
204
205
206
   ]
  },
  {
   "cell_type": "code",
Chayenne's avatar
Chayenne committed
207
   "execution_count": null,
208
   "metadata": {},
Chayenne's avatar
Chayenne committed
209
   "outputs": [],
Lianmin Zheng's avatar
Lianmin Zheng committed
210
211
   "source": [
    "stream = client.chat.completions.create(\n",
212
    "    model=\"qwen/qwen2.5-0.5b-instruct\",\n",
Lianmin Zheng's avatar
Lianmin Zheng committed
213
214
215
216
217
218
    "    messages=[{\"role\": \"user\", \"content\": \"Say this is a test\"}],\n",
    "    stream=True,\n",
    ")\n",
    "for chunk in stream:\n",
    "    if chunk.choices[0].delta.content is not None:\n",
    "        print(chunk.choices[0].delta.content, end=\"\")"
Chayenne's avatar
Chayenne committed
219
220
221
222
223
224
225
226
227
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Completions\n",
    "\n",
    "### Usage\n",
228
    "Completions API is similar to Chat Completions API, but without the `messages` parameter or chat templates."
Chayenne's avatar
Chayenne committed
229
230
231
232
   ]
  },
  {
   "cell_type": "code",
Chayenne's avatar
Chayenne committed
233
   "execution_count": null,
234
   "metadata": {},
Chayenne's avatar
Chayenne committed
235
   "outputs": [],
Chayenne's avatar
Chayenne committed
236
237
   "source": [
    "response = client.completions.create(\n",
238
    "    model=\"qwen/qwen2.5-0.5b-instruct\",\n",
Chayenne's avatar
Chayenne committed
239
240
241
242
243
244
    "    prompt=\"List 3 countries and their capitals.\",\n",
    "    temperature=0,\n",
    "    max_tokens=64,\n",
    "    n=1,\n",
    "    stop=None,\n",
    ")\n",
245
246
    "\n",
    "print_highlight(f\"Response: {response}\")"
Chayenne's avatar
Chayenne committed
247
248
249
250
251
252
253
254
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Parameters\n",
    "\n",
255
    "The completions API accepts OpenAI Completions API's parameters.  Refer to [OpenAI Completions API](https://platform.openai.com/docs/api-reference/completions/create) for more details.\n",
Chayenne's avatar
Chayenne committed
256
257
258
259
260
261
    "\n",
    "Here is an example of a detailed completions request:"
   ]
  },
  {
   "cell_type": "code",
Chayenne's avatar
Chayenne committed
262
   "execution_count": null,
263
   "metadata": {},
Chayenne's avatar
Chayenne committed
264
   "outputs": [],
Chayenne's avatar
Chayenne committed
265
266
   "source": [
    "response = client.completions.create(\n",
267
    "    model=\"qwen/qwen2.5-0.5b-instruct\",\n",
Chayenne's avatar
Chayenne committed
268
269
270
271
272
273
274
275
276
277
278
    "    prompt=\"Write a short story about a space explorer.\",\n",
    "    temperature=0.7,  # Moderate temperature for creative writing\n",
    "    max_tokens=150,  # Longer response for a story\n",
    "    top_p=0.9,  # Balanced diversity in word choice\n",
    "    stop=[\"\\n\\n\", \"THE END\"],  # Multiple stop sequences\n",
    "    presence_penalty=0.3,  # Encourage novel elements\n",
    "    frequency_penalty=0.3,  # Reduce repetitive phrases\n",
    "    n=1,  # Generate one completion\n",
    "    seed=123,  # For reproducible results\n",
    ")\n",
    "\n",
279
    "print_highlight(f\"Response: {response}\")"
Chayenne's avatar
Chayenne committed
280
281
   ]
  },
Lianmin Zheng's avatar
Lianmin Zheng committed
282
283
284
285
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
286
    "## Structured Outputs (JSON, Regex, EBNF)\n",
287
    "\n",
288
    "For OpenAI compatible structured outputs API, refer to [Structured Outputs](https://docs.sglang.ai/backend/structured_outputs.html#OpenAI-Compatible-API) for more details.\n"
289
290
   ]
  },
Chayenne's avatar
Chayenne committed
291
292
  {
   "cell_type": "code",
293
294
   "execution_count": null,
   "metadata": {},
Lianmin Zheng's avatar
Lianmin Zheng committed
295
   "outputs": [],
Chayenne's avatar
Chayenne committed
296
   "source": [
297
    "terminate_process(server_process)"
Chayenne's avatar
Chayenne committed
298
299
300
301
   ]
  }
 ],
 "metadata": {
Chayenne's avatar
Chayenne committed
302
303
304
305
306
307
308
309
310
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
311
   "pygments_lexer": "ipython3"
Chayenne's avatar
Chayenne committed
312
313
314
315
316
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}