Skip to main content
SGLang provides a set of generation primitives that control how the LLM generates text and processes inputs. These primitives are the building blocks for creating complex prompting workflows.

Text Generation

sgl.gen() - Generate Text

The primary primitive for generating text from the model. Basic Usage:
Signature:
Parameters:
  • name (str): Variable name to store the generated text. Access via state[name]
  • max_tokens (int): Maximum number of tokens to generate
  • min_tokens (int): Minimum number of tokens to generate
  • stop (str | List[str]): Stop sequence(s) to end generation
  • stop_token_ids (List[int]): Token IDs that trigger stop
  • stop_regex (str | List[str]): Regular expression patterns to stop generation
  • temperature (float): Sampling temperature (0.0 = greedy, higher = more random)
  • top_p (float): Nucleus sampling threshold
  • top_k (int): Top-k sampling parameter
  • min_p (float): Minimum probability threshold
  • frequency_penalty (float): Penalty for token frequency
  • presence_penalty (float): Penalty for token presence
  • ignore_eos (bool): Ignore end-of-sequence token
  • regex (str): Regular expression to constrain output format
  • json_schema (str): JSON schema for structured output
  • choices (List[str]): List of choices (equivalent to select())
  • return_logprob (bool): Return log probabilities
  • logprob_start_len (int): Position to start returning logprobs
  • top_logprobs_num (int): Number of top logprobs to return
  • return_text_in_logprobs (bool): Include text in logprob results
Examples: Stop Sequences:
Multiple Stop Sequences:
Temperature Control:
Minimum Tokens:

Typed Generation

SGLang provides convenience functions for generating specific data types: sgl.gen_int() - Generate Integer
sgl.gen_string() - Generate String

Constrained Generation

Regular Expression Constraints

Use regex to enforce specific output formats:
Email Address:
Phone Number:

JSON Schema Constraints

Generate structured JSON output:
Complex Schema Example:

Choice Selection

sgl.select() - Choose from Options

Select the most likely option from a list of choices:
Signature:
Parameters:
  • name (str): Variable name for the selected choice
  • choices (List[str]): List of possible choices
  • temperature (float): Sampling temperature (usually 0.0 for deterministic selection)
  • choices_method (ChoicesSamplingMethod): Method for scoring choices
Using choices in gen(): Alternatively, use the choices parameter in gen():
Conditional Logic with Choices:

Multimodal Primitives

sgl.image() - Add Image Input

Add an image to the prompt for vision models:
Signature:
Parameters:
  • path (str): Path to image file or base64-encoded image data
Multiple Images:

sgl.video() - Add Video Input

Add a video to the prompt for video-capable models:
Signature:
Parameters:
  • path (str): Path to video file
  • num_frames (int): Number of frames to sample from the video

Role Management Primitives

For chat models, structure conversations with role primitives:

sgl.system() - System Message

sgl.user() - User Message

sgl.assistant() - Assistant Message

Role Context Managers

For complex role structures, use context managers:
Available Role Methods:
  • sgl.system() / s.system()
  • sgl.user() / s.user()
  • sgl.assistant() / s.assistant()
  • sgl.system_begin() / sgl.system_end()
  • sgl.user_begin() / sgl.user_end()
  • sgl.assistant_begin() / sgl.assistant_end()

Advanced Primitives

Separate Reasoning

For models that support chain-of-thought reasoning with special tokens:

Complete Examples

Question Answering with Constraints

Multimodal Analysis

Best Practices

  1. Name your variables: Always provide a name parameter to access generated content
  2. Use stop sequences: Prevent over-generation with appropriate stop tokens
  3. Set max_tokens: Always set reasonable limits to avoid runaway generation
  4. Use constraints wisely: Regex and JSON schemas ensure format compliance
  5. Choose appropriate temperature: 0.0 for factual, higher for creative tasks
  6. Test constraints: Verify regex patterns work as expected before production use