OpenAI APIs - Completions#

SGLang provides OpenAI-compatible APIs to enable a smooth transition from OpenAI services to self-hosted local models. A complete reference for the API is available in the OpenAI API Reference.

This tutorial covers the following popular APIs:

  • chat/completions

  • completions

  • batches

Check out other tutorials to learn about vision APIs for vision-language models and embedding APIs for embedding models.

Launch A Server#

Launch the server in your terminal and wait for it to initialize.

[1]:
from sglang.test.test_utils import is_in_ci

if is_in_ci():
    from patch import launch_server_cmd
else:
    from sglang.utils import launch_server_cmd

from sglang.utils import wait_for_server, print_highlight, terminate_process


server_process, port = launch_server_cmd(
    "python3 -m sglang.launch_server --model-path qwen/qwen2.5-0.5b-instruct --host 0.0.0.0 --mem-fraction-static 0.8"
)

wait_for_server(f"http://localhost:{port}")
print(f"Server started on http://localhost:{port}")
[2025-06-14 19:50:06] server_args=ServerArgs(model_path='qwen/qwen2.5-0.5b-instruct', tokenizer_path='qwen/qwen2.5-0.5b-instruct', tokenizer_mode='auto', skip_tokenizer_init=False, load_format='auto', trust_remote_code=False, dtype='auto', kv_cache_dtype='auto', quantization=None, quantization_param_path=None, context_length=None, device='cuda', served_model_name='qwen/qwen2.5-0.5b-instruct', chat_template=None, completion_template=None, is_embedding=False, enable_multimodal=None, revision=None, impl='auto', host='0.0.0.0', port=35600, mem_fraction_static=0.8, max_running_requests=200, max_total_tokens=20480, chunked_prefill_size=8192, max_prefill_tokens=16384, schedule_policy='fcfs', schedule_conservativeness=1.0, cpu_offload_gb=0, page_size=1, tp_size=1, pp_size=1, max_micro_batch_size=None, stream_interval=1, stream_output=False, random_seed=284820657, constrained_json_whitespace_pattern=None, watchdog_timeout=300, dist_timeout=None, download_dir=None, base_gpu_id=0, gpu_id_step=1, sleep_on_idle=False, log_level='info', log_level_http=None, log_requests=False, log_requests_level=0, show_time_cost=False, enable_metrics=False, bucket_time_to_first_token=None, bucket_e2e_request_latency=None, bucket_inter_token_latency=None, collect_tokens_histogram=False, decode_log_interval=40, enable_request_time_stats_logging=False, kv_events_config=None, api_key=None, file_storage_path='sglang_storage', enable_cache_report=False, reasoning_parser=None, tool_call_parser=None, dp_size=1, load_balance_method='round_robin', dist_init_addr=None, nnodes=1, node_rank=0, json_model_override_args='{}', preferred_sampling_params=None, lora_paths=None, max_loras_per_batch=8, lora_backend='triton', attention_backend=None, sampling_backend='flashinfer', grammar_backend='xgrammar', mm_attention_backend=None, speculative_algorithm=None, speculative_draft_model_path=None, speculative_num_steps=None, speculative_eagle_topk=None, speculative_num_draft_tokens=None, speculative_accept_threshold_single=1.0, speculative_accept_threshold_acc=1.0, speculative_token_map=None, ep_size=1, enable_ep_moe=False, enable_deepep_moe=False, deepep_mode='auto', ep_num_redundant_experts=0, ep_dispatch_algorithm='static', init_expert_location='trivial', enable_eplb=False, eplb_algorithm='auto', eplb_rebalance_num_iterations=1000, eplb_rebalance_layers_per_chunk=None, expert_distribution_recorder_mode=None, expert_distribution_recorder_buffer_size=1000, enable_expert_distribution_metrics=False, deepep_config=None, moe_dense_tp_size=None, enable_double_sparsity=False, ds_channel_config_path=None, ds_heavy_channel_num=32, ds_heavy_token_num=256, ds_heavy_channel_type='qk', ds_sparse_decode_threshold=4096, disable_radix_cache=False, cuda_graph_max_bs=None, cuda_graph_bs=None, disable_cuda_graph=True, disable_cuda_graph_padding=False, enable_profile_cuda_graph=False, enable_nccl_nvls=False, enable_tokenizer_batch_encode=False, disable_outlines_disk_cache=False, disable_custom_all_reduce=False, enable_mscclpp=False, disable_overlap_schedule=False, disable_overlap_cg_plan=False, enable_mixed_chunk=False, enable_dp_attention=False, enable_dp_lm_head=False, enable_two_batch_overlap=False, enable_torch_compile=False, torch_compile_max_bs=32, torchao_config='', enable_nan_detection=False, enable_p2p_check=False, triton_attention_reduce_in_fp32=False, triton_attention_num_kv_splits=8, num_continuous_decode_steps=1, delete_ckpt_after_loading=False, enable_memory_saver=False, allow_auto_truncate=False, enable_custom_logit_processor=False, enable_hierarchical_cache=False, hicache_ratio=2.0, hicache_size=0, hicache_write_policy='write_through_selective', flashinfer_mla_disable_ragged=False, disable_shared_experts_fusion=False, disable_chunked_prefix_cache=False, disable_fast_image_processor=False, enable_return_hidden_states=False, warmups=None, debug_tensor_dump_output_folder=None, debug_tensor_dump_input_file=None, debug_tensor_dump_inject=False, debug_tensor_dump_prefill_only=False, disaggregation_mode='null', disaggregation_transfer_backend='mooncake', disaggregation_bootstrap_port=8998, disaggregation_ib_device=None, num_reserved_decode_tokens=512, pdlb_url=None)
[2025-06-14 19:50:17] Attention backend not set. Use fa3 backend by default.
[2025-06-14 19:50:17] Init torch distributed begin.
[2025-06-14 19:50:17] Init torch distributed ends. mem usage=0.00 GB
[2025-06-14 19:50:18] Load weight begin. avail mem=60.49 GB
[2025-06-14 19:50:18] Using model weights format ['*.safetensors']
[2025-06-14 19:50:18] No model.safetensors.index.json found in remote.
Loading safetensors checkpoint shards:   0% Completed | 0/1 [00:00<?, ?it/s]
Loading safetensors checkpoint shards: 100% Completed | 1/1 [00:00<00:00,  5.34it/s]
Loading safetensors checkpoint shards: 100% Completed | 1/1 [00:00<00:00,  5.34it/s]

[2025-06-14 19:50:18] Load weight end. type=Qwen2ForCausalLM, dtype=torch.bfloat16, avail mem=59.52 GB, mem usage=0.98 GB.
[2025-06-14 19:50:18] KV Cache is allocated. #tokens: 20480, K size: 0.12 GB, V size: 0.12 GB
[2025-06-14 19:50:18] Memory pool end. avail mem=59.11 GB
[2025-06-14 19:50:19] max_total_num_tokens=20480, chunked_prefill_size=8192, max_prefill_tokens=16384, max_running_requests=200, context_len=32768, available_gpu_mem=59.01 GB
[2025-06-14 19:50:19] INFO:     Started server process [1577700]
[2025-06-14 19:50:19] INFO:     Waiting for application startup.
[2025-06-14 19:50:19] INFO:     Application startup complete.
[2025-06-14 19:50:19] INFO:     Uvicorn running on http://0.0.0.0:35600 (Press CTRL+C to quit)
[2025-06-14 19:50:20] INFO:     127.0.0.1:60476 - "GET /v1/models HTTP/1.1" 200 OK
[2025-06-14 19:50:20] INFO:     127.0.0.1:60486 - "GET /get_model_info HTTP/1.1" 200 OK
[2025-06-14 19:50:20] Prefill batch. #new-seq: 1, #new-token: 6, #cached-token: 0, token usage: 0.00, #running-req: 0, #queue-req: 0
[2025-06-14 19:50:22] INFO:     127.0.0.1:60490 - "POST /generate HTTP/1.1" 200 OK
[2025-06-14 19:50:22] The server is fired up and ready to roll!


NOTE: Typically, the server runs in a separate terminal.
In this notebook, we run the server and notebook code together, so their outputs are combined.
To improve clarity, the server logs are displayed in the original black color, while the notebook outputs are highlighted in blue.
We are running those notebooks in a CI parallel environment, so the throughput is not representative of the actual performance.
Server started on http://localhost:35600

Chat Completions#

Usage#

The server fully implements the OpenAI API. It will automatically apply the chat template specified in the Hugging Face tokenizer, if one is available. You can also specify a custom chat template with --chat-template when launching the server.

[2]:
import openai

client = openai.Client(base_url=f"http://127.0.0.1:{port}/v1", api_key="None")

response = client.chat.completions.create(
    model="qwen/qwen2.5-0.5b-instruct",
    messages=[
        {"role": "user", "content": "List 3 countries and their capitals."},
    ],
    temperature=0,
    max_tokens=64,
)

print_highlight(f"Response: {response}")
[2025-06-14 19:50:25] Detected chat template content format: string
[2025-06-14 19:50:25] Prefill batch. #new-seq: 1, #new-token: 37, #cached-token: 0, token usage: 0.00, #running-req: 0, #queue-req: 0
[2025-06-14 19:50:26] Decode batch. #running-req: 1, #token: 70, token usage: 0.00, cuda graph: False, gen throughput (token/s): 5.88, #queue-req: 0
[2025-06-14 19:50:26] INFO:     127.0.0.1:60506 - "POST /v1/chat/completions HTTP/1.1" 200 OK
Response: ChatCompletion(id='ce7d93501e504f038b9634426176e7db', choices=[Choice(finish_reason='stop', index=0, logprobs=None, message=ChatCompletionMessage(content='Sure, here are three countries and their respective capitals:\n\n1. **United States** - Washington, D.C.\n2. **Canada** - Ottawa\n3. **Australia** - Canberra', refusal=None, role='assistant', annotations=None, audio=None, function_call=None, tool_calls=None, reasoning_content=None), matched_stop=151645)], created=1749930625, model='qwen/qwen2.5-0.5b-instruct', object='chat.completion', service_tier=None, system_fingerprint=None, usage=CompletionUsage(completion_tokens=39, prompt_tokens=37, total_tokens=76, completion_tokens_details=None, prompt_tokens_details=None))

Parameters#

The chat completions API accepts OpenAI Chat Completions API’s parameters. Refer to OpenAI Chat Completions API for more details.

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.

Enabling Model Thinking/Reasoning#

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 (e.g., --reasoning-parser qwen3 for Qwen3 models).

Here’s an example demonstrating how to enable thinking and retrieve the reasoning content separately (using separate_reasoning: True):

# Ensure the server is launched with a compatible reasoning parser, e.g.:
# python3 -m sglang.launch_server --model-path QwQ/Qwen3-32B-250415 --reasoning-parser qwen3 ...

from openai import OpenAI

# Modify OpenAI's API key and API base to use SGLang's API server.
openai_api_key = "EMPTY"
openai_api_base = f"http://127.0.0.1:{port}/v1" # Use the correct port

client = OpenAI(
    api_key=openai_api_key,
    base_url=openai_api_base,
)

model = "QwQ/Qwen3-32B-250415" # Use the model loaded by the server
messages = [{"role": "user", "content": "9.11 and 9.8, which is greater?"}]

response = client.chat.completions.create(
    model=model,
    messages=messages,
    extra_body={
        "chat_template_kwargs": {"enable_thinking": True},
        "separate_reasoning": True
    }
)

print("response.choices[0].message.reasoning_content: \n", response.choices[0].message.reasoning_content)
print("response.choices[0].message.content: \n", response.choices[0].message.content)

Example Output:

response.choices[0].message.reasoning_content:
 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.
...
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.

response.choices[0].message.content:
 To determine which number is greater between **9.11** and **9.8**, follow these steps:
...
**Answer**:
9.8 is greater than 9.11.

Setting "enable_thinking": False (or omitting it) will result in reasoning_content being None.

Here is an example of a detailed chat completion request using standard OpenAI parameters:

[3]:
response = client.chat.completions.create(
    model="qwen/qwen2.5-0.5b-instruct",
    messages=[
        {
            "role": "system",
            "content": "You are a knowledgeable historian who provides concise responses.",
        },
        {"role": "user", "content": "Tell me about ancient Rome"},
        {
            "role": "assistant",
            "content": "Ancient Rome was a civilization centered in Italy.",
        },
        {"role": "user", "content": "What were their major achievements?"},
    ],
    temperature=0.3,  # Lower temperature for more focused responses
    max_tokens=128,  # Reasonable length for a concise response
    top_p=0.95,  # Slightly higher for better fluency
    presence_penalty=0.2,  # Mild penalty to avoid repetition
    frequency_penalty=0.2,  # Mild penalty for more natural language
    n=1,  # Single response is usually more stable
    seed=42,  # Keep for reproducibility
)

print_highlight(response.choices[0].message.content)
[2025-06-14 19:50:26] Prefill batch. #new-seq: 1, #new-token: 49, #cached-token: 5, token usage: 0.00, #running-req: 0, #queue-req: 0
[2025-06-14 19:50:26] Decode batch. #running-req: 1, #token: 88, token usage: 0.00, cuda graph: False, gen throughput (token/s): 85.56, #queue-req: 0
[2025-06-14 19:50:26] Decode batch. #running-req: 1, #token: 128, token usage: 0.01, cuda graph: False, gen throughput (token/s): 125.99, #queue-req: 0
[2025-06-14 19:50:27] Decode batch. #running-req: 1, #token: 168, token usage: 0.01, cuda graph: False, gen throughput (token/s): 126.20, #queue-req: 0
[2025-06-14 19:50:27] INFO:     127.0.0.1:60506 - "POST /v1/chat/completions HTTP/1.1" 200 OK
Ancient Rome was a major civilization that had a profound impact on the world. Some of their major achievements include:

1. The construction of the Colosseum, which was a massive amphitheater in Rome that hosted gladiatorial contests and other public spectacles.

2. The development of Roman law, which established a system of legal principles and procedures that were later adopted by many other cultures.

3. The construction of the Pantheon, which was a temple dedicated to Jupiter and other gods in Rome.

4. The invention of the metron, a timekeeping device that was used to measure the duration of events and festivals.

Streaming mode is also supported.

[4]:
stream = client.chat.completions.create(
    model="qwen/qwen2.5-0.5b-instruct",
    messages=[{"role": "user", "content": "Say this is a test"}],
    stream=True,
)
for chunk in stream:
    if chunk.choices[0].delta.content is not None:
        print(chunk.choices[0].delta.content, end="")
[2025-06-14 19:50:27] INFO:     127.0.0.1:60506 - "POST /v1/chat/completions HTTP/1.1" 200 OK
[2025-06-14 19:50:27] Prefill batch. #new-seq: 1, #new-token: 10, #cached-token: 24, token usage: 0.00, #running-req: 0, #queue-req: 0
Yes, I'm an AI language model created by Alibaba Cloud. I'm designed to provide information and assistance on various topics,[2025-06-14 19:50:27] Decode batch. #running-req: 1, #token: 60, token usage: 0.00, cuda graph: False, gen throughput (token/s): 115.41, #queue-req: 0
 and I'm not a test.

Completions#

Usage#

Completions API is similar to Chat Completions API, but without the messages parameter or chat templates.

[5]:
response = client.completions.create(
    model="qwen/qwen2.5-0.5b-instruct",
    prompt="List 3 countries and their capitals.",
    temperature=0,
    max_tokens=64,
    n=1,
    stop=None,
)

print_highlight(f"Response: {response}")
[2025-06-14 19:50:27] Prefill batch. #new-seq: 1, #new-token: 8, #cached-token: 0, token usage: 0.00, #running-req: 0, #queue-req: 0
[2025-06-14 19:50:27] Decode batch. #running-req: 1, #token: 41, token usage: 0.00, cuda graph: False, gen throughput (token/s): 104.87, #queue-req: 0
[2025-06-14 19:50:28] INFO:     127.0.0.1:60506 - "POST /v1/completions HTTP/1.1" 200 OK
Response: Completion(id='e1772938c45449089a295ab0072fb989', choices=[CompletionChoice(finish_reason='length', index=0, logprobs=None, text=' 1. United States - Washington D.C.\n2. Canada - Ottawa\n3. France - Paris\n4. Germany - Berlin\n5. Japan - Tokyo\n6. Italy - Rome\n7. Spain - Madrid\n8. United Kingdom - London\n9. Australia - Canberra\n10. New Zealand', matched_stop=None)], created=1749930627, model='qwen/qwen2.5-0.5b-instruct', object='text_completion', system_fingerprint=None, usage=CompletionUsage(completion_tokens=64, prompt_tokens=8, total_tokens=72, completion_tokens_details=None, prompt_tokens_details=None))

Parameters#

The completions API accepts OpenAI Completions API’s parameters. Refer to OpenAI Completions API for more details.

Here is an example of a detailed completions request:

[6]:
response = client.completions.create(
    model="qwen/qwen2.5-0.5b-instruct",
    prompt="Write a short story about a space explorer.",
    temperature=0.7,  # Moderate temperature for creative writing
    max_tokens=150,  # Longer response for a story
    top_p=0.9,  # Balanced diversity in word choice
    stop=["\n\n", "THE END"],  # Multiple stop sequences
    presence_penalty=0.3,  # Encourage novel elements
    frequency_penalty=0.3,  # Reduce repetitive phrases
    n=1,  # Generate one completion
    seed=123,  # For reproducible results
)

print_highlight(f"Response: {response}")
[2025-06-14 19:50:28] Prefill batch. #new-seq: 1, #new-token: 9, #cached-token: 0, token usage: 0.00, #running-req: 0, #queue-req: 0
[2025-06-14 19:50:28] Decode batch. #running-req: 1, #token: 18, token usage: 0.00, cuda graph: False, gen throughput (token/s): 73.94, #queue-req: 0
[2025-06-14 19:50:28] Decode batch. #running-req: 1, #token: 58, token usage: 0.00, cuda graph: False, gen throughput (token/s): 119.30, #queue-req: 0
[2025-06-14 19:50:28] INFO:     127.0.0.1:60506 - "POST /v1/completions HTTP/1.1" 200 OK
Response: Completion(id='3a93e7a1ca754bafbce1ae352eb0ecb3', choices=[CompletionChoice(finish_reason='stop', index=0, logprobs=None, text=' Once upon a time, there was a space explorer named Jack who had been on many missions in space. He loved the feeling of exploring the stars and the thrill of the unknown. One day, he was sent on a mission to explore a newly discovered planet that was known to be teeming with life.', matched_stop='\n\n')], created=1749930628, model='qwen/qwen2.5-0.5b-instruct', object='text_completion', system_fingerprint=None, usage=CompletionUsage(completion_tokens=61, prompt_tokens=9, total_tokens=70, completion_tokens_details=None, prompt_tokens_details=None))

Structured Outputs (JSON, Regex, EBNF)#

For OpenAI compatible structured outputs API, refer to Structured Outputs for more details.

Batches#

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).

The batches APIs are:

  • batches

  • batches/{batch_id}/cancel

  • batches/{batch_id}

Here is an example of a batch job for chat completions, completions are similar.

[7]:
import json
import time
from openai import OpenAI

client = OpenAI(base_url=f"http://127.0.0.1:{port}/v1", api_key="None")

requests = [
    {
        "custom_id": "request-1",
        "method": "POST",
        "url": "/chat/completions",
        "body": {
            "model": "qwen/qwen2.5-0.5b-instruct",
            "messages": [
                {"role": "user", "content": "Tell me a joke about programming"}
            ],
            "max_tokens": 50,
        },
    },
    {
        "custom_id": "request-2",
        "method": "POST",
        "url": "/chat/completions",
        "body": {
            "model": "qwen/qwen2.5-0.5b-instruct",
            "messages": [{"role": "user", "content": "What is Python?"}],
            "max_tokens": 50,
        },
    },
]

input_file_path = "batch_requests.jsonl"

with open(input_file_path, "w") as f:
    for req in requests:
        f.write(json.dumps(req) + "\n")

with open(input_file_path, "rb") as f:
    file_response = client.files.create(file=f, purpose="batch")

batch_response = client.batches.create(
    input_file_id=file_response.id,
    endpoint="/v1/chat/completions",
    completion_window="24h",
)

print_highlight(f"Batch job created with ID: {batch_response.id}")
[2025-06-14 19:50:28] INFO:     127.0.0.1:60518 - "POST /v1/files HTTP/1.1" 200 OK
[2025-06-14 19:50:29] INFO:     127.0.0.1:60518 - "POST /v1/batches HTTP/1.1" 200 OK
Batch job created with ID: batch_87ef5aa3-c226-429a-aef6-b2d92e77e29b
[2025-06-14 19:50:29] Prefill batch. #new-seq: 2, #new-token: 20, #cached-token: 48, token usage: 0.00, #running-req: 0, #queue-req: 0
[8]:
while batch_response.status not in ["completed", "failed", "cancelled"]:
    time.sleep(3)
    print(f"Batch job status: {batch_response.status}...trying again in 3 seconds...")
    batch_response = client.batches.retrieve(batch_response.id)

if batch_response.status == "completed":
    print("Batch job completed successfully!")
    print(f"Request counts: {batch_response.request_counts}")

    result_file_id = batch_response.output_file_id
    file_response = client.files.content(result_file_id)
    result_content = file_response.read().decode("utf-8")

    results = [
        json.loads(line) for line in result_content.split("\n") if line.strip() != ""
    ]

    for result in results:
        print_highlight(f"Request {result['custom_id']}:")
        print_highlight(f"Response: {result['response']}")

    print_highlight("Cleaning up files...")
    # Only delete the result file ID since file_response is just content
    client.files.delete(result_file_id)
else:
    print_highlight(f"Batch job failed with status: {batch_response.status}")
    if hasattr(batch_response, "errors"):
        print_highlight(f"Errors: {batch_response.errors}")
[2025-06-14 19:50:29] Decode batch. #running-req: 2, #token: 100, token usage: 0.00, cuda graph: False, gen throughput (token/s): 81.92, #queue-req: 0
Batch job status: validating...trying again in 3 seconds...
[2025-06-14 19:50:32] INFO:     127.0.0.1:60518 - "GET /v1/batches/batch_87ef5aa3-c226-429a-aef6-b2d92e77e29b HTTP/1.1" 200 OK
Batch job completed successfully!
Request counts: BatchRequestCounts(completed=2, failed=0, total=2)
[2025-06-14 19:50:32] INFO:     127.0.0.1:60518 - "GET /v1/files/backend_result_file-fe6aa6f7-9389-4995-bcf4-485463dc5fa0/content HTTP/1.1" 200 OK
Request request-1:
Response: {'status_code': 200, 'request_id': 'batch_87ef5aa3-c226-429a-aef6-b2d92e77e29b-req_0', 'body': {'id': 'batch_87ef5aa3-c226-429a-aef6-b2d92e77e29b-req_0', 'object': 'chat.completion', 'created': 1749930629, 'model': 'qwen/qwen2.5-0.5b-instruct', 'choices': {'index': 0, 'message': {'role': 'assistant', 'content': 'Sure! Here\'s a programming joke for you:\nWhy don\'t programmers trust computers?\n\nBecause they always say "yes, and" and "no, or."\nI hope that brings a smile to your face!', 'tool_calls': None, 'reasoning_content': None}, 'logprobs': None, 'finish_reason': 'stop', 'matched_stop': 151645}, 'usage': {'prompt_tokens': 35, 'completion_tokens': 43, 'total_tokens': 78}, 'system_fingerprint': None}}
Request request-2:
Response: {'status_code': 200, 'request_id': 'batch_87ef5aa3-c226-429a-aef6-b2d92e77e29b-req_1', 'body': {'id': 'batch_87ef5aa3-c226-429a-aef6-b2d92e77e29b-req_1', 'object': 'chat.completion', 'created': 1749930629, 'model': 'qwen/qwen2.5-0.5b-instruct', 'choices': {'index': 0, 'message': {'role': 'assistant', 'content': 'Python is a high-level, general-purpose programming language created by Guido Van Rossum and first released in 1991. It is known for its simplicity and readability, making it easy for beginners to learn and use. Python is widely used', 'tool_calls': None, 'reasoning_content': None}, 'logprobs': None, 'finish_reason': 'length', 'matched_stop': None}, 'usage': {'prompt_tokens': 33, 'completion_tokens': 50, 'total_tokens': 83}, 'system_fingerprint': None}}
Cleaning up files...
[2025-06-14 19:50:32] INFO:     127.0.0.1:60518 - "DELETE /v1/files/backend_result_file-fe6aa6f7-9389-4995-bcf4-485463dc5fa0 HTTP/1.1" 200 OK

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.

  1. batches/{batch_id}: Retrieve the batch job status.

  2. batches/{batch_id}/cancel: Cancel the batch job.

Here is an example to check the batch job status.

[9]:
import json
import time
from openai import OpenAI

client = OpenAI(base_url=f"http://127.0.0.1:{port}/v1", api_key="None")

requests = []
for i in range(20):
    requests.append(
        {
            "custom_id": f"request-{i}",
            "method": "POST",
            "url": "/chat/completions",
            "body": {
                "model": "qwen/qwen2.5-0.5b-instruct",
                "messages": [
                    {
                        "role": "system",
                        "content": f"{i}: You are a helpful AI assistant",
                    },
                    {
                        "role": "user",
                        "content": "Write a detailed story about topic. Make it very long.",
                    },
                ],
                "max_tokens": 64,
            },
        }
    )

input_file_path = "batch_requests.jsonl"
with open(input_file_path, "w") as f:
    for req in requests:
        f.write(json.dumps(req) + "\n")

with open(input_file_path, "rb") as f:
    uploaded_file = client.files.create(file=f, purpose="batch")

batch_job = client.batches.create(
    input_file_id=uploaded_file.id,
    endpoint="/v1/chat/completions",
    completion_window="24h",
)

print_highlight(f"Created batch job with ID: {batch_job.id}")
print_highlight(f"Initial status: {batch_job.status}")

time.sleep(10)

max_checks = 5
for i in range(max_checks):
    batch_details = client.batches.retrieve(batch_id=batch_job.id)

    print_highlight(
        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}"
    )
    print_highlight(
        f"<strong>Request counts: Total: {batch_details.request_counts.total} // Completed: {batch_details.request_counts.completed} // Failed: {batch_details.request_counts.failed}</strong>"
    )

    time.sleep(3)
[2025-06-14 19:50:32] INFO:     127.0.0.1:59210 - "POST /v1/files HTTP/1.1" 200 OK
[2025-06-14 19:50:32] INFO:     127.0.0.1:59210 - "POST /v1/batches HTTP/1.1" 200 OK
Created batch job with ID: batch_c7b9995d-a14e-4f10-9c4d-f57017cf70fc
Initial status: validating
[2025-06-14 19:50:32] Prefill batch. #new-seq: 10, #new-token: 300, #cached-token: 30, token usage: 0.00, #running-req: 0, #queue-req: 0
[2025-06-14 19:50:32] Prefill batch. #new-seq: 10, #new-token: 310, #cached-token: 30, token usage: 0.01, #running-req: 10, #queue-req: 0
[2025-06-14 19:50:32] Decode batch. #running-req: 19, #token: 915, token usage: 0.04, cuda graph: False, gen throughput (token/s): 137.19, #queue-req: 0
[2025-06-14 19:50:32] Decode batch. #running-req: 18, #token: 1588, token usage: 0.08, cuda graph: False, gen throughput (token/s): 2200.37, #queue-req: 0
[2025-06-14 19:50:42] INFO:     127.0.0.1:58560 - "GET /v1/batches/batch_c7b9995d-a14e-4f10-9c4d-f57017cf70fc HTTP/1.1" 200 OK
Batch job details (check 1 / 5) // ID: batch_c7b9995d-a14e-4f10-9c4d-f57017cf70fc // Status: completed // Created at: 1749930632 // Input file ID: backend_input_file-8c6f1ea7-58ce-4303-bc8f-74c7a3f475ed // Output file ID: backend_result_file-6c2b3781-7df7-4fcb-ab4f-1c3207746179
Request counts: Total: 20 // Completed: 20 // Failed: 0
[2025-06-14 19:50:45] INFO:     127.0.0.1:58560 - "GET /v1/batches/batch_c7b9995d-a14e-4f10-9c4d-f57017cf70fc HTTP/1.1" 200 OK
Batch job details (check 2 / 5) // ID: batch_c7b9995d-a14e-4f10-9c4d-f57017cf70fc // Status: completed // Created at: 1749930632 // Input file ID: backend_input_file-8c6f1ea7-58ce-4303-bc8f-74c7a3f475ed // Output file ID: backend_result_file-6c2b3781-7df7-4fcb-ab4f-1c3207746179
Request counts: Total: 20 // Completed: 20 // Failed: 0
[2025-06-14 19:50:48] INFO:     127.0.0.1:58560 - "GET /v1/batches/batch_c7b9995d-a14e-4f10-9c4d-f57017cf70fc HTTP/1.1" 200 OK
Batch job details (check 3 / 5) // ID: batch_c7b9995d-a14e-4f10-9c4d-f57017cf70fc // Status: completed // Created at: 1749930632 // Input file ID: backend_input_file-8c6f1ea7-58ce-4303-bc8f-74c7a3f475ed // Output file ID: backend_result_file-6c2b3781-7df7-4fcb-ab4f-1c3207746179
Request counts: Total: 20 // Completed: 20 // Failed: 0
[2025-06-14 19:50:51] INFO:     127.0.0.1:58560 - "GET /v1/batches/batch_c7b9995d-a14e-4f10-9c4d-f57017cf70fc HTTP/1.1" 200 OK
Batch job details (check 4 / 5) // ID: batch_c7b9995d-a14e-4f10-9c4d-f57017cf70fc // Status: completed // Created at: 1749930632 // Input file ID: backend_input_file-8c6f1ea7-58ce-4303-bc8f-74c7a3f475ed // Output file ID: backend_result_file-6c2b3781-7df7-4fcb-ab4f-1c3207746179
Request counts: Total: 20 // Completed: 20 // Failed: 0
[2025-06-14 19:50:54] INFO:     127.0.0.1:58560 - "GET /v1/batches/batch_c7b9995d-a14e-4f10-9c4d-f57017cf70fc HTTP/1.1" 200 OK
Batch job details (check 5 / 5) // ID: batch_c7b9995d-a14e-4f10-9c4d-f57017cf70fc // Status: completed // Created at: 1749930632 // Input file ID: backend_input_file-8c6f1ea7-58ce-4303-bc8f-74c7a3f475ed // Output file ID: backend_result_file-6c2b3781-7df7-4fcb-ab4f-1c3207746179
Request counts: Total: 20 // Completed: 20 // Failed: 0

Here is an example to cancel a batch job.

[10]:
import json
import time
from openai import OpenAI
import os

client = OpenAI(base_url=f"http://127.0.0.1:{port}/v1", api_key="None")

requests = []
for i in range(5000):
    requests.append(
        {
            "custom_id": f"request-{i}",
            "method": "POST",
            "url": "/chat/completions",
            "body": {
                "model": "qwen/qwen2.5-0.5b-instruct",
                "messages": [
                    {
                        "role": "system",
                        "content": f"{i}: You are a helpful AI assistant",
                    },
                    {
                        "role": "user",
                        "content": "Write a detailed story about topic. Make it very long.",
                    },
                ],
                "max_tokens": 128,
            },
        }
    )

input_file_path = "batch_requests.jsonl"
with open(input_file_path, "w") as f:
    for req in requests:
        f.write(json.dumps(req) + "\n")

with open(input_file_path, "rb") as f:
    uploaded_file = client.files.create(file=f, purpose="batch")

batch_job = client.batches.create(
    input_file_id=uploaded_file.id,
    endpoint="/v1/chat/completions",
    completion_window="24h",
)

print_highlight(f"Created batch job with ID: {batch_job.id}")
print_highlight(f"Initial status: {batch_job.status}")

time.sleep(10)

try:
    cancelled_job = client.batches.cancel(batch_id=batch_job.id)
    print_highlight(f"Cancellation initiated. Status: {cancelled_job.status}")
    assert cancelled_job.status == "cancelling"

    # Monitor the cancellation process
    while cancelled_job.status not in ["failed", "cancelled"]:
        time.sleep(3)
        cancelled_job = client.batches.retrieve(batch_job.id)
        print_highlight(f"Current status: {cancelled_job.status}")

    # Verify final status
    assert cancelled_job.status == "cancelled"
    print_highlight("Batch job successfully cancelled")

except Exception as e:
    print_highlight(f"Error during cancellation: {e}")
    raise e

finally:
    try:
        del_response = client.files.delete(uploaded_file.id)
        if del_response.deleted:
            print_highlight("Successfully cleaned up input file")
        if os.path.exists(input_file_path):
            os.remove(input_file_path)
            print_highlight("Successfully deleted local batch_requests.jsonl file")
    except Exception as e:
        print_highlight(f"Error cleaning up: {e}")
        raise e
[2025-06-14 19:50:57] INFO:     127.0.0.1:56518 - "POST /v1/files HTTP/1.1" 200 OK
[2025-06-14 19:50:57] INFO:     127.0.0.1:56518 - "POST /v1/batches HTTP/1.1" 200 OK
Created batch job with ID: batch_15f5697a-d44d-4fbe-946c-bf31db917c04
Initial status: validating
[2025-06-14 19:50:58] Prefill batch. #new-seq: 32, #new-token: 380, #cached-token: 698, token usage: 0.03, #running-req: 0, #queue-req: 0
[2025-06-14 19:50:58] Prefill batch. #new-seq: 105, #new-token: 3150, #cached-token: 457, token usage: 0.05, #running-req: 32, #queue-req: 362
[2025-06-14 19:50:58] Prefill batch. #new-seq: 24, #new-token: 720, #cached-token: 120, token usage: 0.29, #running-req: 136, #queue-req: 4839
[2025-06-14 19:50:58] Decode batch. #running-req: 160, #token: 9843, token usage: 0.48, cuda graph: False, gen throughput (token/s): 193.75, #queue-req: 4839
[2025-06-14 19:50:58] Prefill batch. #new-seq: 2, #new-token: 60, #cached-token: 10, token usage: 0.48, #running-req: 159, #queue-req: 4837
[2025-06-14 19:50:59] Prefill batch. #new-seq: 1, #new-token: 30, #cached-token: 5, token usage: 0.52, #running-req: 160, #queue-req: 4836
[2025-06-14 19:50:59] Prefill batch. #new-seq: 1, #new-token: 30, #cached-token: 5, token usage: 0.54, #running-req: 159, #queue-req: 4835
[2025-06-14 19:50:59] Decode batch. #running-req: 159, #token: 16054, token usage: 0.78, cuda graph: False, gen throughput (token/s): 14933.27, #queue-req: 4835
[2025-06-14 19:50:59] KV cache pool is full. Retract requests. #retracted_reqs: 23, #new_token_ratio: 0.5977 -> 0.9499
[2025-06-14 19:50:59] Decode batch. #running-req: 135, #token: 19387, token usage: 0.95, cuda graph: False, gen throughput (token/s): 15719.95, #queue-req: 4858
[2025-06-14 19:50:59] KV cache pool is full. Retract requests. #retracted_reqs: 16, #new_token_ratio: 0.9308 -> 1.0000
[2025-06-14 19:50:59] Prefill batch. #new-seq: 10, #new-token: 300, #cached-token: 50, token usage: 0.89, #running-req: 119, #queue-req: 4864
[2025-06-14 19:50:59] Prefill batch. #new-seq: 119, #new-token: 3574, #cached-token: 591, token usage: 0.02, #running-req: 10, #queue-req: 4745
[2025-06-14 19:51:00] Decode batch. #running-req: 129, #token: 7174, token usage: 0.35, cuda graph: False, gen throughput (token/s): 11194.33, #queue-req: 4745
[2025-06-14 19:51:00] Prefill batch. #new-seq: 4, #new-token: 120, #cached-token: 20, token usage: 0.37, #running-req: 128, #queue-req: 4741
[2025-06-14 19:51:00] Decode batch. #running-req: 132, #token: 12507, token usage: 0.61, cuda graph: False, gen throughput (token/s): 13056.60, #queue-req: 4741
[2025-06-14 19:51:00] Prefill batch. #new-seq: 2, #new-token: 60, #cached-token: 10, token usage: 0.62, #running-req: 131, #queue-req: 4739
[2025-06-14 19:51:00] Prefill batch. #new-seq: 1, #new-token: 32, #cached-token: 3, token usage: 0.64, #running-req: 132, #queue-req: 4738
[2025-06-14 19:51:01] Decode batch. #running-req: 132, #token: 17585, token usage: 0.86, cuda graph: False, gen throughput (token/s): 12768.12, #queue-req: 4738
[2025-06-14 19:51:01] Prefill batch. #new-seq: 8, #new-token: 240, #cached-token: 40, token usage: 0.90, #running-req: 122, #queue-req: 4730
[2025-06-14 19:51:01] Prefill batch. #new-seq: 114, #new-token: 3556, #cached-token: 434, token usage: 0.05, #running-req: 15, #queue-req: 4616
[2025-06-14 19:51:01] Prefill batch. #new-seq: 14, #new-token: 427, #cached-token: 63, token usage: 0.30, #running-req: 128, #queue-req: 4602
[2025-06-14 19:51:01] Decode batch. #running-req: 142, #token: 7006, token usage: 0.34, cuda graph: False, gen throughput (token/s): 10789.57, #queue-req: 4602
[2025-06-14 19:51:01] Prefill batch. #new-seq: 5, #new-token: 152, #cached-token: 23, token usage: 0.39, #running-req: 138, #queue-req: 4597
[2025-06-14 19:51:01] Prefill batch. #new-seq: 2, #new-token: 60, #cached-token: 10, token usage: 0.46, #running-req: 142, #queue-req: 4595
[2025-06-14 19:51:01] Decode batch. #running-req: 142, #token: 11983, token usage: 0.59, cuda graph: False, gen throughput (token/s): 13825.52, #queue-req: 4595
[2025-06-14 19:51:02] Prefill batch. #new-seq: 1, #new-token: 30, #cached-token: 5, token usage: 0.65, #running-req: 139, #queue-req: 4594
[2025-06-14 19:51:02] Prefill batch. #new-seq: 1, #new-token: 30, #cached-token: 5, token usage: 0.66, #running-req: 139, #queue-req: 4593
[2025-06-14 19:51:02] Decode batch. #running-req: 140, #token: 17175, token usage: 0.84, cuda graph: False, gen throughput (token/s): 14267.31, #queue-req: 4593
[2025-06-14 19:51:02] KV cache pool is full. Retract requests. #retracted_reqs: 19, #new_token_ratio: 0.7452 -> 1.0000
[2025-06-14 19:51:02] Prefill batch. #new-seq: 8, #new-token: 248, #cached-token: 32, token usage: 0.89, #running-req: 121, #queue-req: 4604
[2025-06-14 19:51:02] Prefill batch. #new-seq: 8, #new-token: 242, #cached-token: 38, token usage: 0.86, #running-req: 121, #queue-req: 4596
[2025-06-14 19:51:02] Prefill batch. #new-seq: 108, #new-token: 3410, #cached-token: 370, token usage: 0.06, #running-req: 20, #queue-req: 4488
[2025-06-14 19:51:02] Decode batch. #running-req: 128, #token: 5339, token usage: 0.26, cuda graph: False, gen throughput (token/s): 11277.79, #queue-req: 4488
[2025-06-14 19:51:02] Prefill batch. #new-seq: 7, #new-token: 217, #cached-token: 28, token usage: 0.27, #running-req: 124, #queue-req: 4481
[2025-06-14 19:51:03] Prefill batch. #new-seq: 2, #new-token: 60, #cached-token: 10, token usage: 0.40, #running-req: 130, #queue-req: 4479
[2025-06-14 19:51:03] Prefill batch. #new-seq: 2, #new-token: 61, #cached-token: 9, token usage: 0.43, #running-req: 131, #queue-req: 4477
[2025-06-14 19:51:03] Prefill batch. #new-seq: 1, #new-token: 30, #cached-token: 5, token usage: 0.47, #running-req: 132, #queue-req: 4476
[2025-06-14 19:51:03] Decode batch. #running-req: 133, #token: 10104, token usage: 0.49, cuda graph: False, gen throughput (token/s): 12196.62, #queue-req: 4476
[2025-06-14 19:51:03] Prefill batch. #new-seq: 1, #new-token: 30, #cached-token: 5, token usage: 0.58, #running-req: 132, #queue-req: 4475
[2025-06-14 19:51:03] Prefill batch. #new-seq: 1, #new-token: 30, #cached-token: 5, token usage: 0.66, #running-req: 132, #queue-req: 4474
[2025-06-14 19:51:03] Decode batch. #running-req: 133, #token: 15302, token usage: 0.75, cuda graph: False, gen throughput (token/s): 14002.34, #queue-req: 4474
[2025-06-14 19:51:03] Prefill batch. #new-seq: 5, #new-token: 150, #cached-token: 25, token usage: 0.90, #running-req: 125, #queue-req: 4469
[2025-06-14 19:51:03] Prefill batch. #new-seq: 8, #new-token: 247, #cached-token: 33, token usage: 0.86, #running-req: 122, #queue-req: 4461
[2025-06-14 19:51:03] Decode batch. #running-req: 130, #token: 18446, token usage: 0.90, cuda graph: False, gen throughput (token/s): 12987.71, #queue-req: 4461
[2025-06-14 19:51:04] Prefill batch. #new-seq: 104, #new-token: 3322, #cached-token: 318, token usage: 0.11, #running-req: 26, #queue-req: 4357
[2025-06-14 19:51:04] Prefill batch. #new-seq: 19, #new-token: 580, #cached-token: 85, token usage: 0.29, #running-req: 123, #queue-req: 4338
[2025-06-14 19:51:04] Prefill batch. #new-seq: 4, #new-token: 124, #cached-token: 16, token usage: 0.44, #running-req: 139, #queue-req: 4334
[2025-06-14 19:51:04] Decode batch. #running-req: 143, #token: 9531, token usage: 0.47, cuda graph: False, gen throughput (token/s): 11606.64, #queue-req: 4334
[2025-06-14 19:51:04] Prefill batch. #new-seq: 2, #new-token: 60, #cached-token: 10, token usage: 0.47, #running-req: 141, #queue-req: 4332
[2025-06-14 19:51:04] Prefill batch. #new-seq: 2, #new-token: 60, #cached-token: 10, token usage: 0.48, #running-req: 142, #queue-req: 4330
[2025-06-14 19:51:04] Prefill batch. #new-seq: 1, #new-token: 30, #cached-token: 5, token usage: 0.50, #running-req: 142, #queue-req: 4329
[2025-06-14 19:51:04] Prefill batch. #new-seq: 1, #new-token: 30, #cached-token: 5, token usage: 0.50, #running-req: 142, #queue-req: 4328
[2025-06-14 19:51:04] Prefill batch. #new-seq: 1, #new-token: 31, #cached-token: 4, token usage: 0.60, #running-req: 141, #queue-req: 4327
[2025-06-14 19:51:04] Decode batch. #running-req: 141, #token: 14656, token usage: 0.72, cuda graph: False, gen throughput (token/s): 13642.55, #queue-req: 4327
[2025-06-14 19:51:05] Decode batch. #running-req: 141, #token: 20296, token usage: 0.99, cuda graph: False, gen throughput (token/s): 15328.20, #queue-req: 4327
[2025-06-14 19:51:05] Prefill batch. #new-seq: 3, #new-token: 90, #cached-token: 15, token usage: 0.92, #running-req: 128, #queue-req: 4324
[2025-06-14 19:51:05] Prefill batch. #new-seq: 97, #new-token: 3032, #cached-token: 363, token usage: 0.21, #running-req: 33, #queue-req: 4227
[2025-06-14 19:51:05] Prefill batch. #new-seq: 40, #new-token: 1231, #cached-token: 169, token usage: 0.28, #running-req: 110, #queue-req: 4187
[2025-06-14 19:51:05] Prefill batch. #new-seq: 7, #new-token: 210, #cached-token: 35, token usage: 0.43, #running-req: 149, #queue-req: 4180
[2025-06-14 19:51:05] Decode batch. #running-req: 156, #token: 9475, token usage: 0.46, cuda graph: False, gen throughput (token/s): 10227.13, #queue-req: 4180
[2025-06-14 19:51:05] Prefill batch. #new-seq: 2, #new-token: 60, #cached-token: 10, token usage: 0.47, #running-req: 155, #queue-req: 4178
[2025-06-14 19:51:05] Prefill batch. #new-seq: 3, #new-token: 93, #cached-token: 12, token usage: 0.47, #running-req: 154, #queue-req: 4175
[2025-06-14 19:51:05] Prefill batch. #new-seq: 4, #new-token: 120, #cached-token: 20, token usage: 0.45, #running-req: 153, #queue-req: 4171
[2025-06-14 19:51:05] Prefill batch. #new-seq: 2, #new-token: 60, #cached-token: 10, token usage: 0.49, #running-req: 155, #queue-req: 4169
[2025-06-14 19:51:05] Prefill batch. #new-seq: 2, #new-token: 61, #cached-token: 9, token usage: 0.50, #running-req: 155, #queue-req: 4167
[2025-06-14 19:51:05] Prefill batch. #new-seq: 2, #new-token: 60, #cached-token: 10, token usage: 0.51, #running-req: 156, #queue-req: 4165
[2025-06-14 19:51:06] Decode batch. #running-req: 155, #token: 14182, token usage: 0.69, cuda graph: False, gen throughput (token/s): 13108.11, #queue-req: 4165
[2025-06-14 19:51:06] Decode batch. #running-req: 154, #token: 20281, token usage: 0.99, cuda graph: False, gen throughput (token/s): 16492.86, #queue-req: 4165
[2025-06-14 19:51:06] KV cache pool is full. Retract requests. #retracted_reqs: 24, #new_token_ratio: 0.6217 -> 0.9894
[2025-06-14 19:51:06] Prefill batch. #new-seq: 2, #new-token: 62, #cached-token: 8, token usage: 0.93, #running-req: 127, #queue-req: 4187
[2025-06-14 19:51:06] Prefill batch. #new-seq: 91, #new-token: 2902, #cached-token: 283, token usage: 0.25, #running-req: 37, #queue-req: 4096
[2025-06-14 19:51:06] Prefill batch. #new-seq: 39, #new-token: 1255, #cached-token: 135, token usage: 0.19, #running-req: 92, #queue-req: 4057
[2025-06-14 19:51:07] Decode batch. #running-req: 131, #token: 6076, token usage: 0.30, cuda graph: False, gen throughput (token/s): 10562.14, #queue-req: 4057
[2025-06-14 19:51:07] Prefill batch. #new-seq: 4, #new-token: 120, #cached-token: 24, token usage: 0.33, #running-req: 130, #queue-req: 4053
[2025-06-14 19:51:07] Prefill batch. #new-seq: 1, #new-token: 30, #cached-token: 6, token usage: 0.43, #running-req: 133, #queue-req: 4052
[2025-06-14 19:51:07] Prefill batch. #new-seq: 2, #new-token: 62, #cached-token: 10, token usage: 0.45, #running-req: 132, #queue-req: 4050
[2025-06-14 19:51:07] INFO:     127.0.0.1:60900 - "POST /v1/batches/batch_15f5697a-d44d-4fbe-946c-bf31db917c04/cancel HTTP/1.1" 200 OK
Cancellation initiated. Status: cancelling
[2025-06-14 19:51:10] INFO:     127.0.0.1:60900 - "GET /v1/batches/batch_15f5697a-d44d-4fbe-946c-bf31db917c04 HTTP/1.1" 200 OK
Current status: cancelled
Batch job successfully cancelled
[2025-06-14 19:51:10] INFO:     127.0.0.1:60900 - "DELETE /v1/files/backend_input_file-f4a9e297-d9a2-4019-8b46-abe03ab39eb5 HTTP/1.1" 200 OK
Successfully cleaned up input file
Successfully deleted local batch_requests.jsonl file
[11]:
terminate_process(server_process)
[2025-06-14 19:51:10] Child process unexpectedly failed with exitcode=9. pid=1578040