Jump to content

Connect SuperML | Leeroopedia MCP: Equip your AI agents with best practices, code verification, and debugging knowledge. Powered by Leeroo — building Organizational Superintelligence. Contact us at founders@leeroo.com.

Implementation:Farama Foundation Gymnasium Text Space

From Leeroopedia
Knowledge Sources
Domains Reinforcement_Learning, Spaces
Last Updated 2026-02-15 03:00 GMT

Overview

Concrete tool for representing textual string observations and actions provided by Gymnasium.

Description

The Text space represents strings of characters drawn from a specified character set, with length bounded between min_length and max_length (both inclusive). The default character set is the alphanumeric set (uppercase and lowercase English letters plus digits 0-9).

Each sample is a Python str of random length (uniformly drawn between the bounds) composed of characters uniformly sampled from the character set. Sampling can be controlled via:

  • A mask -- a 2-tuple of (length, charlist_mask) where length fixes the string length and charlist_mask is an np.int8 array of 0/1 values selecting allowed characters.
  • A probability -- a 2-tuple of (length, charlist_probability) where charlist_probability is an np.float64 array specifying per-character sampling probabilities (must sum to 1).

The space is numpy-flattenable (is_np_flattenable returns True). Flattening produces an np.int32 array of length max_length where each position holds the character index (or a padding value for positions beyond the string length).

The dtype of the space is str, and the shape is None because string length is dynamic.

Usage

Use Text when the observation or action is a variable-length string, such as natural language commands, textual descriptions, generated code, or any environment where string I/O is required.

Code Reference

Source Location

Signature

class Text(Space[str]):
    def __init__(
        self,
        max_length: int,
        *,
        min_length: int = 1,
        charset: frozenset[str] | str = alphanumeric,
        seed: int | np.random.Generator | None = None,
    )

Import

from gymnasium.spaces import Text

I/O Contract

Inputs

Name Type Required Description
max_length int Yes Maximum string length (inclusive).
min_length int No Minimum string length (inclusive). Defaults to 1. Must be non-negative and not exceed max_length.
charset frozenset[str] or str No The set of valid characters. Defaults to alphanumeric (a-z, A-Z, 0-9).
seed int, np.random.Generator, or None No Optional seed for the random number generator.

Outputs

Name Type Description
sample() returns str A random string with length in [min_length, max_length] composed of characters from the charset.
contains() returns bool Whether a given string has valid length and contains only characters from the charset.

Key Properties and Methods

Member Description
character_set Property returning the frozenset[str] of valid characters.
character_list Property returning a tuple[str, ...] of characters (ordered).
characters Property returning a sorted string of all valid characters.
character_index(char) Returns the unique np.int32 index for a character in the charset.
sample(mask=None, probability=None) Generate a random string. Supports mask and probability tuples of (length, charlist_mask).
contains(x) Check that x is a string within length bounds and composed only of charset characters.

Usage Examples

from gymnasium.spaces import Text
import numpy as np
import string

# Default alphanumeric text space, max length 10
space = Text(max_length=10, seed=42)
sample = space.sample()
print(sample)        # e.g. "aB3xQ"
print(type(sample))  # <class 'str'>
print(len(sample))   # between 1 and 10

# Digits-only text space
digit_space = Text(max_length=5, min_length=1, charset=string.digits, seed=42)
digit_sample = digit_space.sample()
print(digit_sample)  # e.g. "392"

# Fixed-length sampling via mask
fixed = space.sample(mask=(5, None))  # exactly 5 characters
print(len(fixed))  # 5

# Character-restricted sampling via mask
char_mask = np.zeros(len(space.character_set), dtype=np.int8)
char_mask[0] = 1  # allow only the first character
restricted = space.sample(mask=(3, char_mask))
print(restricted)  # e.g. "000" (only the first character in charset)

# Probability-based character sampling
prob_mask = np.ones(len(space.character_set), dtype=np.float64)
prob_mask = prob_mask / prob_mask.sum()  # uniform probability
prob_sample = space.sample(probability=(4, prob_mask))

# Membership check
print("Hello" in space)   # True (if all chars in charset and len <= 10)
print("" in space)        # False (min_length is 1)
print("Hello!!" in space) # False ('!' not in alphanumeric charset)

# Allow empty strings
empty_ok = Text(max_length=5, min_length=0, seed=42)
print("" in empty_ok)  # True

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment