Prerequisites
- Python 3.11+ if you plan to use the OpenAI Python SDK.
Serve
Launch the server using thesglang serve command.
Start the server
- —model-path: Path to the model or model ID.
- —served-model-name: Stable model name exposed by the serving APIs. It defaults to
--model-idwhen set, otherwise--model-path. - —port: HTTP port to listen on (default:
30000). - —api-key: Require
Authorization: Bearer <key>on every endpoint except the health, readiness, and metrics ones. - —admin-api-key: Unlock the admin endpoints (weight updates, LoRA loading, memory release and resume, profiling); they answer HTTP 403 until it is set. Defaults to
SGLANG_ADMIN_API_KEY.
Served model name
--served-model-name separates the public API identity from the checkpoint location. This is useful when replicas use different local mount paths or when a gateway needs one stable model name:
--model-id is not a free-form deployment alias: it selects the registered model configuration for checkpoints whose local path cannot be identified. --served-model-name only controls the name exposed by serving APIs. When both are set, the served name takes precedence for API responses.
Discover the served model
Endpoint:GET /v1/models
Returns the public model name together with diffusion-specific runtime information.
Curl Example:
curl
curl
GET /server_info also reports served_model_name for gateway discovery. Video and action responses use this name when the request does not provide a model explicitly.
Endpoints
Select a request task
GET /v1/models reports task_type (the configured default) and
supported_task_types (the tasks implemented by that configured pipeline).
GET /model_info also reports the supported output_types. A pipeline may
support image and video output on one server when its implementation and
loaded components provide both paths.
Send the optional SGLang extension task_type as a case-insensitive enum name:
Choose only a task in the server’s advertised set. An unsupported task, a task
with the wrong output type for the endpoint, or missing required conditioning
returns HTTP 400. For example,
i2v needs image input, while v2v and f2v
need video input. Model-specific size, frame count, and reference constraints
still apply.
If you omit task_type, the server uses the endpoint and supplied inputs to
choose a compatible task, preferring its default when compatible. It asks for
an explicit task if several alternatives remain (for example v2v versus
f2v). Pipelines with one task keep that task as their default. Sending a
request never changes the server default or subsequent requests.
Prompt enhancement
Image generation, image edits and video creation acceptenhance_prompt=true
when the server is configured with --prompt-enhancer-config. An independent
SRT service rewrites the prompt before diffusion runs. The default is false;
image responses return data[].revised_prompt, and video responses return
revised_prompt. See deployment and model compatibility.
Model-specific request fields
The image and video request schemas contain only OpenAI fields and stable SGLang extensions shared across model families. Put model-specific controls inextra_body when using the OpenAI Python client:
Python
extra_params. SGLang forwards model-specific extensions only when the active
model declares them, so a field for one model family does not silently change
another model.
Image Generation
The server implements an OpenAI-compatible Images API under the/v1/images namespace.
Create an image
Endpoint: POST /v1/images/generations
Request quality
quality selects a cumulative request-level optimization tier: exact keeps the selected deployment’s reference path and all unconditional bit-exact replacements, so output is bit-identical to it in the same environment; lossless additionally enables the request-gated DiT/VAE fusions that keep the reference math and every operand’s precision and only move the rounding; high includes the full lossless set and may also enable model-owned sparse, caching, lower-precision, or other approximate paths. extra-high is accepted as the former name of lossless. The tier does not override separately configured quantization, attention, or caching options. Omit it (or send OpenAI’s default auto) to keep the lossless runtime default. It is distinct from output_quality, which controls only output-file compression. The same extension is accepted by image edits and video requests.
Python Example (b64_json response):
Python
curl
Note For image generation and edits,Edit an image Endpoint:response_format=urlrequires a persistent output directory or cloud storage. If neither is configured, useb64_json; requesting a URL returns HTTP 400.
POST /v1/images/edits
Send a multipart form with a prompt and an input image: upload a file with image, or pass a remote image URL with url. Supplying both adds two inputs. Masked inpainting is not supported: uploading a mask returns HTTP 400.
Uploaded filenames are sanitized, and saved uploads are constrained to the
server’s upload directory. This also applies to image uploads for video and mesh
generation.
Curl Example (b64_json response):
Command
Command
data[].url from the response. A cloud storage URL can be downloaded directly;
resolve a relative URL such as /v1/images/<IMAGE_ID>/content against the server address.
Endpoint: GET /v1/images/{image_id}/content
Curl Example:
Mesh generation (SGLang extension)
For a mesh-generation model,POST /v1/meshes accepts an input image and returns
an asynchronous job. This endpoint is a SGLang extension, not an OpenAI API.
GET /v1/meshes/{id} until status is completed or failed. The content
endpoint, GET /v1/meshes/{id}/content, returns 404 until the job completes
successfully; an unfinished or failed export is not downloadable even if a
partial file exists. When cloud storage is enabled, use the completed job’s
url instead.
Job metadata is process-local and does not survive server restart.
DELETE /v1/meshes/{id} removes the record, not the running generation or its
output files. Manage output retention separately.
Video Generation
The server implements a subset of the OpenAI Videos API under the/v1/videos namespace.
With --input-save-path "", uploads use request-owned temporary directories,
removed on rejection or after the background job exits. Configured input and
output directories remain persistent. Cancelling preparation waits for active
CPU preprocessing to finish before cleanup; it does not abort queued GPU work.
With --output-path "", cloud upload must succeed before a job reports completion.
Create a video (text-to-video)
Endpoint: POST /v1/videos
Python Example:
Python
curl
Command
Command
size requests a width and height. Some pipelines align these dimensions to
their patch grid; see Wan2.2 TI2V 5B
for an example. Wan-Animate-2 treats size as a pixel-area budget instead:
the output keeps the reference image’s
aspect ratio and uses the largest frame with at most width × height pixels whose
sides are multiples of 16, so size=640x800 with a 9:16 reference image yields a
528×944 video. Request a budget with the reference image’s aspect ratio to get a
specific size. Wan-Animate-2 also ignores seconds and num_frames: the output
has as many frames as the (resampled) reference video, generated in chunks of
clip_len frames; see the
Wan-Animate-2 cookbook.
Wan-Animate-2 keeps the reference video’s audio track on the output; the
model-specific enable_audio field (form field or extra_body, default true)
set to false gives a silent output.MP4 encoding
x264_preset picks the libx264 preset for the returned MP4: ultrafast,
superfast, veryfast, faster, fast (the default), medium, slow,
slower, veryslow or placebo. Faster presets finish encoding sooner and
trade file size and fidelity at the same output_compression/output_quality.
Send it at the top level of a JSON body or as a multipart form field;
sglang generate takes --x264-preset.
List videos
Endpoint: GET /v1/videos
Returns up to 20 jobs by default. Set limit from 1 to 100 and order to
asc or desc (default). Responses include first_id, last_id, and
has_more; pass after=last_id to fetch the next page. The same pagination
contract applies to GET /v1/meshes. Pagination bounds each response, not
the number of stored jobs or queued generation requests.
Python Example:
Python
curl
GET /v1/videos/{video_id}
A job is queued until the scheduler starts it, then in_progress, then
completed or failed. progress estimates denoising progress and stays below
100 until the output is ready. Multiple denoising stages, including refinement,
share the progress range equally. This is not an elapsed-time estimate or a
measurement of GPU completion.
Progress updates are best effort and never block generation. They currently
support single-node, monolithic serving; other deployments may remain queued
at 0 until completion. Job metadata is process-local and does not survive an
HTTP server restart.
When load balancing independent HTTP servers, route polling and content requests
to the server that accepted the job. Scheduler DP replicas behind one HTTP server
share its job store; independent HTTP servers do not. Restart recovery, durable
job ownership, and queue admission limits require an external serving layer.
An accepted job continues after the submitting client disconnects. For a bounded
scheduler wait, set --scheduler-rpc-timeout in seconds; it includes queue time
and generation. A timeout marks the job failed but does not cancel GPU work.
On supported deployments, delete the job to request cancellation. Retrying
generation creates another job, so retain and poll the returned ID.
DELETE /v1/videos/{video_id} removes the API record and requests
cancellation: a cancelled queued job does not start. Running jobs check at stage
boundaries and between sampling steps, independently of progress reporting.
All ranks of a replica stop together. If cancellation arrives during encoding or
decoding, that stage may finish, but subsequent stages are skipped once the
request is observed. Rank-only stages check at executor boundaries, not inside
their sampling loops. There is also a check before output finalization is started
or handed to a background thread. Already submitted GPU kernels and ongoing
saves or uploads are not interrupted; the API does not return deleted jobs.
Cancelled jobs are excluded before dynamic batching. Once a batch starts,
it runs to the end unless every member is cancelled.
If a replica’s cancellation channel is not connected or its queue is full,
DELETE returns 503 with Retry-After: 1. The job record remains available;
retry DELETE with the same video ID. A successful DELETE enqueues the command,
not an acknowledgement that GPU work has already stopped. Cancellation is best
effort: process failures or eviction from the driver’s bounded history (the
latest 4096 cancelled job IDs) can still prevent it. Cancellation supports single-node,
monolithic serving only; in other deployments DELETE removes the API record
without stopping GPU work. Completed jobs can be deleted without a cancellation
channel.
Deleting a job does not remove files that were already generated. Manage output
retention separately.
Python Example:
Python
curl
GET /v1/videos/{video_id}/content
Python Example:
Python
curl
Action generation (SGLang extension)
Action policies use/v1/actions rather than the image or video endpoints.
Launch a supported policy with sglang serve and use its cookbook recipe for
the observation schema, action layout, and sampling defaults.
See the cookbook’s action policies for Pi0.5, FLUX 3 Action,
Praxis-1, and Motubrain 2.0 recipes, or Cosmos3 policy and inverse dynamics
for world-model action generation. Supported inputs, session behavior, and
transports depend on the policy; consult its metadata and recipe before use.
LoRA Management
The server supports dynamic loading, merging, and unmerging of LoRA adapters./v1/set_lora, /v1/merge_lora_weights, and /v1/unmerge_lora_weights are admin endpoints. Launch the server with --admin-api-key <key> (or SGLANG_ADMIN_API_KEY=<key> set) and send Authorization: Bearer <key> with each call; without an admin key configured, the server answers HTTP 403 (--api-key does not unlock them). The examples below read the key from $SGLANG_ADMIN_API_KEY.
Important Notes:
- Mutual Exclusion: Only one LoRA configuration can be active per target at a time; that configuration can contain multiple adapters
- Switching: To switch LoRAs, deactivate the current LoRA with
unmerge_lora_weights, thensetthe new one - Caching: The server caches loaded LoRA weights in memory. Switching back to a previously loaded LoRA (same path) has little cost
merge_mode is omitted, the request inherits the server’s --lora-merge-mode. The default policy, auto, merges regular weights but uses dynamic LoRA for FSDP-sharded weights, supported quantized or AMX-packed weights that cannot merge in place, and updates estimated to lose more than 50% of their norm to merge rounding. These rules also apply to multiple adapters. Forcing merge fails for weights that cannot merge in place; dynamic leaves the base weights unchanged and adds the adapters’ updates during each forward pass. Dynamic LoRA does not retain a separate copy of the base weights. You can still switch to merge later: the layer keeps the original weights only while merged so that unmerging restores them exactly.
Endpoint: POST /v1/set_lora
Parameters:
lora_nickname(string or list of strings, required): A unique identifier for the LoRA adapter(s). Can be a single string or a list of strings for multiple LoRAslora_path(string or list of strings/None, optional): Path to the.safetensorsfile(s) or Hugging Face repo ID(s). Required for the first load; optional if re-activating a cached nickname. If a list, must match the length oflora_nicknametarget(string or list of strings, optional): Which transformer(s) to apply the LoRA to. If a list, must match the length oflora_nickname. Valid values:"all"(default): Apply to all transformers"transformer": Apply only to the primary transformer (high noise for Wan2.2)"transformer_2": Apply only to transformer_2 (low noise for Wan2.2)"critic": Apply only to the critic model
strength(float or list of floats, optional): LoRA strength for static merge or dynamic execution, default 1.0. If a list, must match the length oflora_nickname. Values < 1.0 reduce the effect, values > 1.0 amplify the effectmerge_mode(string, optional):"auto","merge"(force static merge), or"dynamic"(apply LoRA at forward time). If omitted, inherits--lora-merge-mode
Command
Command
Command
When using multiple LoRAs:
- All list parameters (
lora_nickname,lora_path,target,strength) must have the same length - If
targetorstrengthis a single value, it will be applied to all LoRAs - Multiple LoRAs applied to the same target are applied in order
With FSDP-sharded weights, manual merge may require a full-gather and can OOM. Use
set_lora with merge_mode="auto" or "dynamic" for the lower-peak path.POST /v1/merge_lora_weights
Parameters:
target(string, optional): Which transformer(s) to merge. One of “all” (default), “transformer”, “transformer_2”, “critic”strength(float, optional): LoRA strength for merge, default 1.0. Values < 1.0 reduce the effect, values > 1.0 amplify the effect
POST /v1/unmerge_lora_weights
Curl Example:
GET /v1/list_loras
Curl Example:
- If LoRA is not enabled for the current pipeline, the server will return an error.
num_lora_layers_with_weightscounts only layers that have LoRA weights applied for the active adapter.
Example: Switching LoRAs
- Set LoRA A:
Command
- Generate with LoRA A…
- Unmerge LoRA A:
Command
- Set LoRA B:
Command
- Generate with LoRA B…
Adjust Output Quality
The server supports adjusting output quality and compression levels for both image and video generation through theoutput-quality and output-compression parameters.
Parameters
-
output-quality(string, optional): Preset quality level that automatically sets compression. Default is"default". Valid values:"maximum": Highest quality (100)"high": High quality (90)"medium": Medium quality (55)"low": Lower quality (35)"default": Auto-adjust based on media type (50 for video, 75 for image)
-
output-compression(integer, optional): Direct compression level override (0-100). Default isNone. When provided (notNone), takes precedence overoutput-quality.0: Lowest quality, smallest file size100: Highest quality, largest file size
Notes
- Precedence: When both
output-qualityandoutput-compressionare provided,output-compressiontakes precedence - Format Support: Quality settings apply to JPEG, and video formats. PNG is lossless: by default it is stored without zlib compression, which encodes fastest but keeps files close to the raw pixel size; an
output-compressionother than 75 selects zlib levelround(output-compression / 100 * 9)instead. Compressed PNGs of 4 MiB or more (about 2048×2048 RGB and larger) are encoded on a thread pool; setSGLANG_DIFFUSION_DISABLE_PARALLEL_PNG=1on the server to use Pillow’s single-threaded encoder. The pixels are identical either way - File Size vs Quality: Lower compression values (or “low” quality preset) produce smaller files but may show visible artifacts
