openai_api_completions.ipynb 23.3 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
16
    "\n",
    "- `chat/completions`\n",
    "- `completions`\n",
    "- `batches`\n",
17
18
    "\n",
    "Check out other tutorials to learn about vision APIs for vision-language models and embedding APIs for embedding models."
Chayenne's avatar
Chayenne committed
19
20
21
22
23
24
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
25
    "## Launch A Server\n",
Chayenne's avatar
Chayenne committed
26
    "\n",
27
    "This code block is equivalent to executing \n",
Chayenne's avatar
Chayenne committed
28
    "\n",
29
30
31
32
33
34
    "```bash\n",
    "python -m sglang.launch_server --model-path meta-llama/Meta-Llama-3.1-8B-Instruct \\\n",
    "--port 30000 --host 0.0.0.0\n",
    "```\n",
    "\n",
    "in your terminal and wait for the server to be ready."
Chayenne's avatar
Chayenne committed
35
36
37
38
   ]
  },
  {
   "cell_type": "code",
Chayenne's avatar
Chayenne committed
39
   "execution_count": null,
40
41
   "metadata": {
    "execution": {
Chayenne's avatar
Chayenne committed
42
43
44
45
     "iopub.execute_input": "2024-11-07T18:46:54.813876Z",
     "iopub.status.busy": "2024-11-07T18:46:54.813741Z",
     "iopub.status.idle": "2024-11-07T18:47:24.015527Z",
     "shell.execute_reply": "2024-11-07T18:47:24.014987Z"
46
47
    }
   },
Chayenne's avatar
Chayenne committed
48
   "outputs": [],
Chayenne's avatar
Chayenne committed
49
   "source": [
50
51
52
53
54
55
    "from sglang.utils import (\n",
    "    execute_shell_command,\n",
    "    wait_for_server,\n",
    "    terminate_process,\n",
    "    print_highlight,\n",
    ")\n",
Chayenne's avatar
Chayenne committed
56
57
    "\n",
    "server_process = execute_shell_command(\n",
Chayenne's avatar
Chayenne committed
58
    "    \"python -m sglang.launch_server --model-path meta-llama/Meta-Llama-3.1-8B-Instruct --port 30000 --host 0.0.0.0\"\n",
Chayenne's avatar
Chayenne committed
59
60
    ")\n",
    "\n",
61
    "wait_for_server(\"http://localhost:30000\")"
Chayenne's avatar
Chayenne committed
62
63
   ]
  },
64
65
66
67
68
69
70
71
72
73
74
75
76
  {
   "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
77
78
  {
   "cell_type": "code",
Chayenne's avatar
Chayenne committed
79
   "execution_count": null,
Chayenne's avatar
Chayenne committed
80
81
   "metadata": {
    "execution": {
Chayenne's avatar
Chayenne committed
82
83
84
85
     "iopub.execute_input": "2024-11-07T18:47:24.018153Z",
     "iopub.status.busy": "2024-11-07T18:47:24.017755Z",
     "iopub.status.idle": "2024-11-07T18:47:25.374821Z",
     "shell.execute_reply": "2024-11-07T18:47:25.374397Z"
Chayenne's avatar
Chayenne committed
86
87
    }
   },
Chayenne's avatar
Chayenne committed
88
   "outputs": [],
Chayenne's avatar
Chayenne committed
89
90
91
92
93
94
95
96
97
98
99
100
101
   "source": [
    "import openai\n",
    "\n",
    "client = openai.Client(base_url=\"http://127.0.0.1:30000/v1\", api_key=\"None\")\n",
    "\n",
    "response = client.chat.completions.create(\n",
    "    model=\"meta-llama/Meta-Llama-3.1-8B-Instruct\",\n",
    "    messages=[\n",
    "        {\"role\": \"user\", \"content\": \"List 3 countries and their capitals.\"},\n",
    "    ],\n",
    "    temperature=0,\n",
    "    max_tokens=64,\n",
    ")\n",
102
103
    "\n",
    "print_highlight(f\"Response: {response}\")"
Chayenne's avatar
Chayenne committed
104
105
106
107
108
109
110
111
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Parameters\n",
    "\n",
112
    "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
113
114
115
116
117
118
    "\n",
    "Here is an example of a detailed chat completion request:"
   ]
  },
  {
   "cell_type": "code",
Chayenne's avatar
Chayenne committed
119
   "execution_count": null,
Chayenne's avatar
Chayenne committed
120
121
   "metadata": {
    "execution": {
Chayenne's avatar
Chayenne committed
122
123
124
125
     "iopub.execute_input": "2024-11-07T18:47:25.376617Z",
     "iopub.status.busy": "2024-11-07T18:47:25.376495Z",
     "iopub.status.idle": "2024-11-07T18:47:28.482537Z",
     "shell.execute_reply": "2024-11-07T18:47:28.482125Z"
Chayenne's avatar
Chayenne committed
126
127
    }
   },
Chayenne's avatar
Chayenne committed
128
   "outputs": [],
Chayenne's avatar
Chayenne committed
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
   "source": [
    "response = client.chat.completions.create(\n",
    "    model=\"meta-llama/Meta-Llama-3.1-8B-Instruct\",\n",
    "    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
145
    "    max_tokens=128,  # Reasonable length for a concise response\n",
Chayenne's avatar
Chayenne committed
146
147
148
149
150
151
152
    "    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
153
154
155
156
157
158
159
    "print_highlight(response.choices[0].message.content)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
Chayenne's avatar
Chayenne committed
160
    "Streaming mode is also supported."
Lianmin Zheng's avatar
Lianmin Zheng committed
161
162
163
164
   ]
  },
  {
   "cell_type": "code",
Chayenne's avatar
Chayenne committed
165
   "execution_count": null,
Chayenne's avatar
Chayenne committed
166
167
   "metadata": {
    "execution": {
Chayenne's avatar
Chayenne committed
168
169
170
171
     "iopub.execute_input": "2024-11-07T18:47:28.484819Z",
     "iopub.status.busy": "2024-11-07T18:47:28.484673Z",
     "iopub.status.idle": "2024-11-07T18:47:28.659814Z",
     "shell.execute_reply": "2024-11-07T18:47:28.659435Z"
Chayenne's avatar
Chayenne committed
172
173
    }
   },
Chayenne's avatar
Chayenne committed
174
   "outputs": [],
Lianmin Zheng's avatar
Lianmin Zheng committed
175
176
177
178
179
180
181
182
183
   "source": [
    "stream = client.chat.completions.create(\n",
    "    model=\"meta-llama/Meta-Llama-3.1-8B-Instruct\",\n",
    "    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
184
185
186
187
188
189
190
191
192
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Completions\n",
    "\n",
    "### Usage\n",
193
    "Completions API is similar to Chat Completions API, but without the `messages` parameter or chat templates."
Chayenne's avatar
Chayenne committed
194
195
196
197
   ]
  },
  {
   "cell_type": "code",
Chayenne's avatar
Chayenne committed
198
   "execution_count": null,
Chayenne's avatar
Chayenne committed
199
200
   "metadata": {
    "execution": {
Chayenne's avatar
Chayenne committed
201
202
203
204
     "iopub.execute_input": "2024-11-07T18:47:28.661844Z",
     "iopub.status.busy": "2024-11-07T18:47:28.661710Z",
     "iopub.status.idle": "2024-11-07T18:47:30.168922Z",
     "shell.execute_reply": "2024-11-07T18:47:30.168600Z"
Chayenne's avatar
Chayenne committed
205
206
    }
   },
Chayenne's avatar
Chayenne committed
207
   "outputs": [],
Chayenne's avatar
Chayenne committed
208
209
210
211
212
213
214
215
216
   "source": [
    "response = client.completions.create(\n",
    "    model=\"meta-llama/Meta-Llama-3.1-8B-Instruct\",\n",
    "    prompt=\"List 3 countries and their capitals.\",\n",
    "    temperature=0,\n",
    "    max_tokens=64,\n",
    "    n=1,\n",
    "    stop=None,\n",
    ")\n",
217
218
    "\n",
    "print_highlight(f\"Response: {response}\")"
Chayenne's avatar
Chayenne committed
219
220
221
222
223
224
225
226
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Parameters\n",
    "\n",
227
    "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
228
229
230
231
232
233
    "\n",
    "Here is an example of a detailed completions request:"
   ]
  },
  {
   "cell_type": "code",
Chayenne's avatar
Chayenne committed
234
   "execution_count": null,
Chayenne's avatar
Chayenne committed
235
236
   "metadata": {
    "execution": {
Chayenne's avatar
Chayenne committed
237
238
239
240
     "iopub.execute_input": "2024-11-07T18:47:30.171319Z",
     "iopub.status.busy": "2024-11-07T18:47:30.171176Z",
     "iopub.status.idle": "2024-11-07T18:47:33.760113Z",
     "shell.execute_reply": "2024-11-07T18:47:33.759713Z"
Chayenne's avatar
Chayenne committed
241
242
    }
   },
Chayenne's avatar
Chayenne committed
243
   "outputs": [],
Chayenne's avatar
Chayenne committed
244
245
246
247
248
249
250
251
252
253
254
255
256
257
   "source": [
    "response = client.completions.create(\n",
    "    model=\"meta-llama/Meta-Llama-3.1-8B-Instruct\",\n",
    "    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",
258
    "print_highlight(f\"Response: {response}\")"
Chayenne's avatar
Chayenne committed
259
260
   ]
  },
Lianmin Zheng's avatar
Lianmin Zheng committed
261
262
263
264
265
266
267
268
269
270
271
272
273
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Structured decoding (JSON, Regex)\n",
    "You can specify a JSON schema or a regular expression to constrain the model output. The model output will be guaranteed to follow the given constraints.\n",
    "\n",
    "### JSON"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
274
275
   "metadata": {
    "execution": {
Chayenne's avatar
Chayenne committed
276
277
278
279
     "iopub.execute_input": "2024-11-07T18:47:33.762729Z",
     "iopub.status.busy": "2024-11-07T18:47:33.762590Z",
     "iopub.status.idle": "2024-11-07T18:47:34.255316Z",
     "shell.execute_reply": "2024-11-07T18:47:34.254907Z"
280
281
    }
   },
Lianmin Zheng's avatar
Lianmin Zheng committed
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
   "outputs": [],
   "source": [
    "import json\n",
    "\n",
    "json_schema = json.dumps(\n",
    "    {\n",
    "        \"type\": \"object\",\n",
    "        \"properties\": {\n",
    "            \"name\": {\"type\": \"string\", \"pattern\": \"^[\\\\w]+$\"},\n",
    "            \"population\": {\"type\": \"integer\"},\n",
    "        },\n",
    "        \"required\": [\"name\", \"population\"],\n",
    "    }\n",
    ")\n",
    "\n",
    "response = client.chat.completions.create(\n",
    "    model=\"meta-llama/Meta-Llama-3.1-8B-Instruct\",\n",
    "    messages=[\n",
Chayenne's avatar
Chayenne committed
300
301
302
303
    "        {\n",
    "            \"role\": \"user\",\n",
    "            \"content\": \"Give me the information of the capital of France in the JSON format.\",\n",
    "        },\n",
Lianmin Zheng's avatar
Lianmin Zheng committed
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
    "    ],\n",
    "    temperature=0,\n",
    "    max_tokens=128,\n",
    "    response_format={\n",
    "        \"type\": \"json_schema\",\n",
    "        \"json_schema\": {\"name\": \"foo\", \"schema\": json.loads(json_schema)},\n",
    "    },\n",
    ")\n",
    "\n",
    "print_highlight(response.choices[0].message.content)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Regular expression"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
326
327
   "metadata": {
    "execution": {
Chayenne's avatar
Chayenne committed
328
329
330
331
     "iopub.execute_input": "2024-11-07T18:47:34.257393Z",
     "iopub.status.busy": "2024-11-07T18:47:34.257246Z",
     "iopub.status.idle": "2024-11-07T18:47:34.413506Z",
     "shell.execute_reply": "2024-11-07T18:47:34.413172Z"
332
333
    }
   },
Lianmin Zheng's avatar
Lianmin Zheng committed
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
   "outputs": [],
   "source": [
    "response = client.chat.completions.create(\n",
    "    model=\"meta-llama/Meta-Llama-3.1-8B-Instruct\",\n",
    "    messages=[\n",
    "        {\"role\": \"user\", \"content\": \"What is the capital of France?\"},\n",
    "    ],\n",
    "    temperature=0,\n",
    "    max_tokens=128,\n",
    "    extra_body={\"regex\": \"(Paris|London)\"},\n",
    ")\n",
    "\n",
    "print_highlight(response.choices[0].message.content)"
   ]
  },
Chayenne's avatar
Chayenne committed
349
350
351
352
353
354
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Batches\n",
    "\n",
355
    "Batches API for chat completions and completions are also supported. You can upload your requests in `jsonl` files, create a batch job, and retrieve the results when the batch job is completed (which takes longer but costs less).\n",
Chayenne's avatar
Chayenne committed
356
357
358
359
360
361
362
363
364
365
366
367
    "\n",
    "The batches APIs are:\n",
    "\n",
    "- `batches`\n",
    "- `batches/{batch_id}/cancel`\n",
    "- `batches/{batch_id}`\n",
    "\n",
    "Here is an example of a batch job for chat completions, completions are similar.\n"
   ]
  },
  {
   "cell_type": "code",
Chayenne's avatar
Chayenne committed
368
   "execution_count": null,
Chayenne's avatar
Chayenne committed
369
370
   "metadata": {
    "execution": {
Chayenne's avatar
Chayenne committed
371
372
373
374
     "iopub.execute_input": "2024-11-07T18:47:34.414816Z",
     "iopub.status.busy": "2024-11-07T18:47:34.414541Z",
     "iopub.status.idle": "2024-11-07T18:47:34.431341Z",
     "shell.execute_reply": "2024-11-07T18:47:34.431081Z"
Chayenne's avatar
Chayenne committed
375
376
    }
   },
Chayenne's avatar
Chayenne committed
377
   "outputs": [],
Chayenne's avatar
Chayenne committed
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
   "source": [
    "import json\n",
    "import time\n",
    "from openai import OpenAI\n",
    "\n",
    "client = OpenAI(base_url=\"http://127.0.0.1:30000/v1\", api_key=\"None\")\n",
    "\n",
    "requests = [\n",
    "    {\n",
    "        \"custom_id\": \"request-1\",\n",
    "        \"method\": \"POST\",\n",
    "        \"url\": \"/chat/completions\",\n",
    "        \"body\": {\n",
    "            \"model\": \"meta-llama/Meta-Llama-3.1-8B-Instruct\",\n",
    "            \"messages\": [\n",
    "                {\"role\": \"user\", \"content\": \"Tell me a joke about programming\"}\n",
    "            ],\n",
    "            \"max_tokens\": 50,\n",
    "        },\n",
    "    },\n",
    "    {\n",
    "        \"custom_id\": \"request-2\",\n",
    "        \"method\": \"POST\",\n",
    "        \"url\": \"/chat/completions\",\n",
    "        \"body\": {\n",
    "            \"model\": \"meta-llama/Meta-Llama-3.1-8B-Instruct\",\n",
    "            \"messages\": [{\"role\": \"user\", \"content\": \"What is Python?\"}],\n",
    "            \"max_tokens\": 50,\n",
    "        },\n",
    "    },\n",
    "]\n",
    "\n",
    "input_file_path = \"batch_requests.jsonl\"\n",
    "\n",
    "with open(input_file_path, \"w\") as f:\n",
    "    for req in requests:\n",
    "        f.write(json.dumps(req) + \"\\n\")\n",
    "\n",
    "with open(input_file_path, \"rb\") as f:\n",
    "    file_response = client.files.create(file=f, purpose=\"batch\")\n",
    "\n",
    "batch_response = client.batches.create(\n",
    "    input_file_id=file_response.id,\n",
    "    endpoint=\"/v1/chat/completions\",\n",
    "    completion_window=\"24h\",\n",
    ")\n",
    "\n",
425
    "print_highlight(f\"Batch job created with ID: {batch_response.id}\")"
Chayenne's avatar
Chayenne committed
426
427
428
429
   ]
  },
  {
   "cell_type": "code",
Chayenne's avatar
Chayenne committed
430
   "execution_count": null,
Chayenne's avatar
Chayenne committed
431
432
   "metadata": {
    "execution": {
Chayenne's avatar
Chayenne committed
433
434
435
436
     "iopub.execute_input": "2024-11-07T18:47:34.432325Z",
     "iopub.status.busy": "2024-11-07T18:47:34.432208Z",
     "iopub.status.idle": "2024-11-07T18:47:37.444337Z",
     "shell.execute_reply": "2024-11-07T18:47:37.444000Z"
Chayenne's avatar
Chayenne committed
437
438
    }
   },
Chayenne's avatar
Chayenne committed
439
   "outputs": [],
Chayenne's avatar
Chayenne committed
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
   "source": [
    "while batch_response.status not in [\"completed\", \"failed\", \"cancelled\"]:\n",
    "    time.sleep(3)\n",
    "    print(f\"Batch job status: {batch_response.status}...trying again in 3 seconds...\")\n",
    "    batch_response = client.batches.retrieve(batch_response.id)\n",
    "\n",
    "if batch_response.status == \"completed\":\n",
    "    print(\"Batch job completed successfully!\")\n",
    "    print(f\"Request counts: {batch_response.request_counts}\")\n",
    "\n",
    "    result_file_id = batch_response.output_file_id\n",
    "    file_response = client.files.content(result_file_id)\n",
    "    result_content = file_response.read().decode(\"utf-8\")\n",
    "\n",
    "    results = [\n",
    "        json.loads(line) for line in result_content.split(\"\\n\") if line.strip() != \"\"\n",
    "    ]\n",
    "\n",
    "    for result in results:\n",
459
460
    "        print_highlight(f\"Request {result['custom_id']}:\")\n",
    "        print_highlight(f\"Response: {result['response']}\")\n",
Chayenne's avatar
Chayenne committed
461
    "\n",
462
    "    print_highlight(\"Cleaning up files...\")\n",
Chayenne's avatar
Chayenne committed
463
464
465
    "    # Only delete the result file ID since file_response is just content\n",
    "    client.files.delete(result_file_id)\n",
    "else:\n",
466
    "    print_highlight(f\"Batch job failed with status: {batch_response.status}\")\n",
Chayenne's avatar
Chayenne committed
467
    "    if hasattr(batch_response, \"errors\"):\n",
468
    "        print_highlight(f\"Errors: {batch_response.errors}\")"
Chayenne's avatar
Chayenne committed
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "It takes a while to complete the batch job. You can use these two APIs to retrieve the batch job status or cancel the batch job.\n",
    "\n",
    "1. `batches/{batch_id}`: Retrieve the batch job status.\n",
    "2. `batches/{batch_id}/cancel`: Cancel the batch job.\n",
    "\n",
    "Here is an example to check the batch job status."
   ]
  },
  {
   "cell_type": "code",
Chayenne's avatar
Chayenne committed
485
   "execution_count": null,
Chayenne's avatar
Chayenne committed
486
487
   "metadata": {
    "execution": {
Chayenne's avatar
Chayenne committed
488
489
490
491
     "iopub.execute_input": "2024-11-07T18:47:37.445894Z",
     "iopub.status.busy": "2024-11-07T18:47:37.445744Z",
     "iopub.status.idle": "2024-11-07T18:48:02.482532Z",
     "shell.execute_reply": "2024-11-07T18:48:02.482042Z"
Chayenne's avatar
Chayenne committed
492
493
    }
   },
Chayenne's avatar
Chayenne committed
494
   "outputs": [],
Chayenne's avatar
Chayenne committed
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
   "source": [
    "import json\n",
    "import time\n",
    "from openai import OpenAI\n",
    "\n",
    "client = OpenAI(base_url=\"http://127.0.0.1:30000/v1\", api_key=\"None\")\n",
    "\n",
    "requests = []\n",
    "for i in range(100):\n",
    "    requests.append(\n",
    "        {\n",
    "            \"custom_id\": f\"request-{i}\",\n",
    "            \"method\": \"POST\",\n",
    "            \"url\": \"/chat/completions\",\n",
    "            \"body\": {\n",
    "                \"model\": \"meta-llama/Meta-Llama-3.1-8B-Instruct\",\n",
    "                \"messages\": [\n",
    "                    {\n",
    "                        \"role\": \"system\",\n",
    "                        \"content\": f\"{i}: You are a helpful AI assistant\",\n",
    "                    },\n",
    "                    {\n",
    "                        \"role\": \"user\",\n",
    "                        \"content\": \"Write a detailed story about topic. Make it very long.\",\n",
    "                    },\n",
    "                ],\n",
    "                \"max_tokens\": 500,\n",
    "            },\n",
    "        }\n",
    "    )\n",
    "\n",
    "input_file_path = \"batch_requests.jsonl\"\n",
    "with open(input_file_path, \"w\") as f:\n",
    "    for req in requests:\n",
    "        f.write(json.dumps(req) + \"\\n\")\n",
    "\n",
    "with open(input_file_path, \"rb\") as f:\n",
    "    uploaded_file = client.files.create(file=f, purpose=\"batch\")\n",
    "\n",
    "batch_job = client.batches.create(\n",
    "    input_file_id=uploaded_file.id,\n",
    "    endpoint=\"/v1/chat/completions\",\n",
    "    completion_window=\"24h\",\n",
    ")\n",
    "\n",
540
541
    "print_highlight(f\"Created batch job with ID: {batch_job.id}\")\n",
    "print_highlight(f\"Initial status: {batch_job.status}\")\n",
Chayenne's avatar
Chayenne committed
542
543
544
545
546
547
    "\n",
    "time.sleep(10)\n",
    "\n",
    "max_checks = 5\n",
    "for i in range(max_checks):\n",
    "    batch_details = client.batches.retrieve(batch_id=batch_job.id)\n",
548
549
550
551
552
553
554
    "\n",
    "    print_highlight(\n",
    "        f\"Batch job details (check {i+1} / {max_checks}) // ID: {batch_details.id} // Status: {batch_details.status} // Created at: {batch_details.created_at} // Input file ID: {batch_details.input_file_id} // Output file ID: {batch_details.output_file_id}\"\n",
    "    )\n",
    "    print_highlight(\n",
    "        f\"<strong>Request counts: Total: {batch_details.request_counts.total} // Completed: {batch_details.request_counts.completed} // Failed: {batch_details.request_counts.failed}</strong>\"\n",
    "    )\n",
Chayenne's avatar
Chayenne committed
555
556
557
558
559
560
561
562
563
564
565
566
567
    "\n",
    "    time.sleep(3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here is an example to cancel a batch job."
   ]
  },
  {
   "cell_type": "code",
Chayenne's avatar
Chayenne committed
568
   "execution_count": null,
Chayenne's avatar
Chayenne committed
569
570
   "metadata": {
    "execution": {
Chayenne's avatar
Chayenne committed
571
572
573
574
     "iopub.execute_input": "2024-11-07T18:48:02.485206Z",
     "iopub.status.busy": "2024-11-07T18:48:02.485064Z",
     "iopub.status.idle": "2024-11-07T18:48:15.521489Z",
     "shell.execute_reply": "2024-11-07T18:48:15.521156Z"
Chayenne's avatar
Chayenne committed
575
576
    }
   },
Chayenne's avatar
Chayenne committed
577
   "outputs": [],
Chayenne's avatar
Chayenne committed
578
579
580
581
   "source": [
    "import json\n",
    "import time\n",
    "from openai import OpenAI\n",
Chayenne's avatar
Chayenne committed
582
    "import os\n",
Chayenne's avatar
Chayenne committed
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
    "\n",
    "client = OpenAI(base_url=\"http://127.0.0.1:30000/v1\", api_key=\"None\")\n",
    "\n",
    "requests = []\n",
    "for i in range(500):\n",
    "    requests.append(\n",
    "        {\n",
    "            \"custom_id\": f\"request-{i}\",\n",
    "            \"method\": \"POST\",\n",
    "            \"url\": \"/chat/completions\",\n",
    "            \"body\": {\n",
    "                \"model\": \"meta-llama/Meta-Llama-3.1-8B-Instruct\",\n",
    "                \"messages\": [\n",
    "                    {\n",
    "                        \"role\": \"system\",\n",
    "                        \"content\": f\"{i}: You are a helpful AI assistant\",\n",
    "                    },\n",
    "                    {\n",
    "                        \"role\": \"user\",\n",
    "                        \"content\": \"Write a detailed story about topic. Make it very long.\",\n",
    "                    },\n",
    "                ],\n",
    "                \"max_tokens\": 500,\n",
    "            },\n",
    "        }\n",
    "    )\n",
    "\n",
    "input_file_path = \"batch_requests.jsonl\"\n",
    "with open(input_file_path, \"w\") as f:\n",
    "    for req in requests:\n",
    "        f.write(json.dumps(req) + \"\\n\")\n",
    "\n",
    "with open(input_file_path, \"rb\") as f:\n",
    "    uploaded_file = client.files.create(file=f, purpose=\"batch\")\n",
    "\n",
    "batch_job = client.batches.create(\n",
    "    input_file_id=uploaded_file.id,\n",
    "    endpoint=\"/v1/chat/completions\",\n",
    "    completion_window=\"24h\",\n",
    ")\n",
    "\n",
624
625
    "print_highlight(f\"Created batch job with ID: {batch_job.id}\")\n",
    "print_highlight(f\"Initial status: {batch_job.status}\")\n",
Chayenne's avatar
Chayenne committed
626
627
628
629
630
    "\n",
    "time.sleep(10)\n",
    "\n",
    "try:\n",
    "    cancelled_job = client.batches.cancel(batch_id=batch_job.id)\n",
631
    "    print_highlight(f\"Cancellation initiated. Status: {cancelled_job.status}\")\n",
Chayenne's avatar
Chayenne committed
632
633
634
635
636
637
    "    assert cancelled_job.status == \"cancelling\"\n",
    "\n",
    "    # Monitor the cancellation process\n",
    "    while cancelled_job.status not in [\"failed\", \"cancelled\"]:\n",
    "        time.sleep(3)\n",
    "        cancelled_job = client.batches.retrieve(batch_job.id)\n",
638
    "        print_highlight(f\"Current status: {cancelled_job.status}\")\n",
Chayenne's avatar
Chayenne committed
639
640
641
    "\n",
    "    # Verify final status\n",
    "    assert cancelled_job.status == \"cancelled\"\n",
642
    "    print_highlight(\"Batch job successfully cancelled\")\n",
Chayenne's avatar
Chayenne committed
643
644
    "\n",
    "except Exception as e:\n",
645
    "    print_highlight(f\"Error during cancellation: {e}\")\n",
Chayenne's avatar
Chayenne committed
646
647
648
649
650
651
    "    raise e\n",
    "\n",
    "finally:\n",
    "    try:\n",
    "        del_response = client.files.delete(uploaded_file.id)\n",
    "        if del_response.deleted:\n",
652
    "            print_highlight(\"Successfully cleaned up input file\")\n",
Chayenne's avatar
Chayenne committed
653
654
655
    "        if os.path.exists(input_file_path):\n",
    "            os.remove(input_file_path)\n",
    "            print_highlight(\"Successfully deleted local batch_requests.jsonl file\")\n",
Chayenne's avatar
Chayenne committed
656
    "    except Exception as e:\n",
657
    "        print_highlight(f\"Error cleaning up: {e}\")\n",
Chayenne's avatar
Chayenne committed
658
659
660
661
662
    "        raise e"
   ]
  },
  {
   "cell_type": "code",
663
   "execution_count": 13,
Chayenne's avatar
Chayenne committed
664
665
   "metadata": {
    "execution": {
Chayenne's avatar
Chayenne committed
666
667
668
669
     "iopub.execute_input": "2024-11-07T18:48:15.522794Z",
     "iopub.status.busy": "2024-11-07T18:48:15.522657Z",
     "iopub.status.idle": "2024-11-07T18:48:16.875740Z",
     "shell.execute_reply": "2024-11-07T18:48:16.874847Z"
Chayenne's avatar
Chayenne committed
670
671
    }
   },
Lianmin Zheng's avatar
Lianmin Zheng committed
672
   "outputs": [],
Chayenne's avatar
Chayenne committed
673
674
675
676
677
678
679
   "source": [
    "terminate_process(server_process)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
Lianmin Zheng's avatar
Lianmin Zheng committed
680
   "display_name": "Python 3 (ipykernel)",
Chayenne's avatar
Chayenne committed
681
682
   "language": "python",
   "name": "python3"
Chayenne's avatar
Chayenne committed
683
684
685
686
687
688
689
690
691
692
693
694
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.7"
Chayenne's avatar
Chayenne committed
695
696
697
698
699
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}