Operators List

This library provides various operators for stream processing.

This section describes unitxt operators.

Operators: Building Blocks of Unitxt Processing Pipelines

Within the Unitxt framework, operators serve as the foundational elements used to assemble processing pipelines. Each operator is designed to perform specific manipulations on dictionary structures within a stream. These operators are callable entities that receive a MultiStream as input. The output is a MultiStream, augmented with the operator’s manipulations, which are then systematically applied to each instance in the stream when pulled.

Creating Custom Operators

To enhance the functionality of Unitxt, users are encouraged to develop custom operators. This can be achieved by inheriting from any of the existing operators listed below or from one of the fundamental base operators. The primary task in any operator development is to implement the process function, which defines the unique manipulations the operator will perform.

General or Specelized Operators

Some operators are specielized in specific task such as:

Other specelized operators are used by unitxt internally:

  • templates for verbalizing data examples.

  • formats for preparing data for models.

The rest of this section is dedicated for general operators.

General Operators List:

class unitxt.operators.AddConstant(__tags__: ~typing.Dict[str, str] = {}, data_classification_policy: ~typing.List[str] = None, caching: bool = None, apply_to_streams: ~typing.List[str] = None, dont_apply_to_streams: ~typing.List[str] = None, field: str | None = None, to_field: str | None = None, field_to_field: ~typing.List[~typing.List[str]] | ~typing.Dict[str, str] | None = None, use_query: bool, process_every_value: bool = False, get_default: ~typing.Any = None, not_exist_ok: bool = False, add: ~typing.Any)

Bases: FieldOperator

Adds a constant, being argument ‘add’, to the processed value.

Parameters:

add – the constant to add.

class unitxt.operators.AddFields(__tags__: ~typing.Dict[str, str] = {}, data_classification_policy: ~typing.List[str] = None, caching: bool = None, apply_to_streams: ~typing.List[str] = None, dont_apply_to_streams: ~typing.List[str] = None, fields: ~typing.Dict[str, object], use_query: bool, use_deepcopy: bool = False)

Bases: InstanceOperator

Adds specified fields to each instance in a given stream or all streams (default) If fields exist, updates them.

Parameters:
  • fields (Dict[str, object]) – The fields to add to each instance. Use ‘/’ to access inner fields

  • use_deepcopy (bool) – Deep copy the input value to avoid later modifications

Examples

# Add a ‘classes’ field with a value of a list “positive” and “negative” to all streams AddFields(fields={“classes”: [“positive”,”negatives”]})

# Add a ‘start’ field under the ‘span’ field with a value of 0 to all streams AddFields(fields={“span/start”: 0}

# Add a ‘classes’ field with a value of a list “positive” and “negative” to ‘train’ stream AddFields(fields={“classes”: [“positive”,”negatives”], apply_to_stream=[“train”]})

# Add a ‘classes’ field on a given list, prevent modification of original list # from changing the instance. AddFields(fields={“classes”: alist}), use_deepcopy=True) # if now alist is modified, still the instances remain intact.

class unitxt.operators.AddID(__tags__: Dict[str, str] = {}, data_classification_policy: List[str] = None, caching: bool = None, apply_to_streams: List[str] = None, dont_apply_to_streams: List[str] = None, id_field_name: str = 'id')

Bases: InstanceOperator

Stores a unique id value in the designated ‘id_field_name’ field of the given instance.

class unitxt.operators.Apply(__tags__: ~typing.Dict[str, str] = {}, data_classification_policy: ~typing.List[str] = None, caching: bool = None, apply_to_streams: ~typing.List[str] = None, dont_apply_to_streams: ~typing.List[str] = None, function: ~typing.Callable, to_field: str, *_argv, **_kwargs)

Bases: InstanceOperator

A class used to apply a python function and store the result in a field.

Parameters:
  • function (additional arguments are field names passed to the) – name of function.

  • to_field (str) – the field to store the result

  • function

Examples: Store in field “b” the uppercase string of the value in field “a” Apply(“a”, function=str.upper, to_field=”b”)

Dump the json representation of field “t” and store back in the same field. Apply(“t”, function=json.dumps, to_field=”t”)

Set the time in a field ‘b’. Apply(function=time.time, to_field=”b”)

class unitxt.operators.ApplyMetric(__tags__: ~typing.Dict[str, str] = {}, data_classification_policy: ~typing.List[str] = None, caching: bool = None, apply_to_streams: ~typing.List[str] = None, dont_apply_to_streams: ~typing.List[str] = None, metric_field: str, calc_confidence_intervals: bool)

Bases: StreamOperator, ArtifactFetcherMixin

Applies metric operators to a stream based on a metric field specified in each instance.

Parameters:
  • metric_field (str) – The field containing the metrics to be applied.

  • calc_confidence_intervals (bool) – Whether the applied metric should calculate confidence intervals or not.

class unitxt.operators.ApplyOperatorsField(__tags__: ~typing.Dict[str, str] = {}, data_classification_policy: ~typing.List[str] = None, caching: bool = None, apply_to_streams: ~typing.List[str] = None, dont_apply_to_streams: ~typing.List[str] = None, operators_field: str, default_operators: ~typing.List[str] = None)

Bases: InstanceOperator

Applies value operators to each instance in a stream based on specified fields.

Parameters:
  • operators_field (str) – name of the field that contains a single name, or a list of names, of the operators to be applied, one after the other, for the processing of the instance. Each operator is equipped with ‘process_instance()’ method.

  • default_operators (List[str]) – A list of default operators to be used if no operators are found in the instance.

Example

when instance {“prediction”: 111, “references”: [222, 333] , “c”: [“processors.to_string”, “processors.first_character”]} is processed by operator (please look up the catalog that these operators, they are tuned to process fields “prediction” and “references”): operator = ApplyOperatorsField(operators_field=”c”), the resulting instance is: {“prediction”: “1”, “references”: [“2”, “3”], “c”: [“processors.to_string”, “processors.first_character”]}

class unitxt.operators.ApplyStreamOperatorsField(__tags__: ~typing.Dict[str, str] = {}, data_classification_policy: ~typing.List[str] = None, caching: bool = None, apply_to_streams: ~typing.List[str] = None, dont_apply_to_streams: ~typing.List[str] = None, field: str, reversed: bool = False)

Bases: StreamOperator, ArtifactFetcherMixin

Applies stream operators to a stream based on specified fields in each instance.

Parameters:
  • field (str) – The field containing the operators to be applied.

  • reversed (bool) – Whether to apply the operators in reverse order.

class unitxt.operators.ArtifactFetcherMixin

Bases: object

Provides a way to fetch and cache artifacts in the system.

Parameters:

cache (Dict[str, Artifact]) – A cache for storing fetched artifacts.

cache: Dict[str, Artifact] = {}
classmethod get_artifact(artifact_identifier: str) Artifact
class unitxt.operators.AugmentPrefixSuffix(__tags__: Dict[str, str] = {}, data_classification_policy: List[str] = None, caching: bool = None, apply_to_streams: List[str] = None, dont_apply_to_streams: List[str] = None, augment_task_input: bool = False, augment_model_input: bool = False, prefixes: List[str] | Dict[str, int] | None = {'': 30, ' ': 20, '\\n': 40, '\\t': 10}, prefix_len: int | None = 3, suffixes: List[str] | Dict[str, int] | None = {'': 30, ' ': 20, '\\n': 40, '\\t': 10}, suffix_len: int | None = 3, remove_existing_whitespaces: bool | None = False)

Bases: Augmentor

Augments the input by prepending and appending to it a randomly selected (typically, whitespace) patterns.

Parameters:
  • prefixes (list or dict) – the potential (typically, whitespace) patterns to select from. The dictionary version allows to specify relative weights of the different patterns.

  • suffixes (list or dict) – the potential (typically, whitespace) patterns to select from. The dictionary version allows to specify relative weights of the different patterns.

  • prefix_len (positive int) – The added prefix or suffix will be of length prefix_len of suffix_len, respectively, repetitions of the randomly selected patterns.

  • suffix_len (positive int) – The added prefix or suffix will be of length prefix_len of suffix_len, respectively, repetitions of the randomly selected patterns.

  • remove_existing_whitespaces – allows to first clean any existing leading and trailing whitespaces. The strings made of repetitions of the selected pattern(s) are then prepended and/or appended to the potentially trimmed input.

  • needed (If only one of prefixes/suffixes is) –

  • None. (set the other to) –

Examples

To prepend the input with a prefix made of 4 ‘n’-s or ‘t’-s, employ AugmentPrefixSuffix(augment_model_input=True, prefixes=[’n’,’t’], prefix_len=4, suffixes = None) To append the input with a suffix made of 3 ‘n’-s or ‘t’-s, with triple ‘n’ suffixes being preferred over triple ‘t’, at 2:1 ratio, employ AugmentPrefixSuffix(augment_model_input=True, suffixes={’n’:2,’t’:1}, suffix_len=3, prefixes = None) which will append ‘n’-s twice as often as ‘t’-s.

prefixes: List[str] | Dict[str, int] | None = {'': 30, ' ': 20, '\\n': 40, '\\t': 10}
suffixes: List[str] | Dict[str, int] | None = {'': 30, ' ': 20, '\\n': 40, '\\t': 10}
class unitxt.operators.AugmentWhitespace(__tags__: Dict[str, str] = {}, data_classification_policy: List[str] = None, caching: bool = None, apply_to_streams: List[str] = None, dont_apply_to_streams: List[str] = None, augment_task_input: bool = False, augment_model_input: bool = False)

Bases: Augmentor

Augments the inputs by replacing existing whitespaces with other whitespaces.

Currently, each whitespace is replaced by a random choice of 1-3 whitespace characters (space, tab, newline).

class unitxt.operators.Augmentor(__tags__: Dict[str, str] = {}, data_classification_policy: List[str] = None, caching: bool = None, apply_to_streams: List[str] = None, dont_apply_to_streams: List[str] = None, augment_task_input: bool = False, augment_model_input: bool = False)

Bases: InstanceOperator

A stream operator that augments the values of either the task input fields before rendering with the template, or the input passed to the model after rendering of the template.

Parameters:
  • augment_model_input – Whether to augment the input to the model.

  • augment_task_input – Whether to augment the task input fields. The specific fields are defined in the Task operator.

class unitxt.operators.CastFields(__tags__: ~typing.Dict[str, str] = {}, data_classification_policy: ~typing.List[str] = None, caching: bool = None, apply_to_streams: ~typing.List[str] = None, dont_apply_to_streams: ~typing.List[str] = None, fields: ~typing.Dict[str, str], failure_defaults: ~typing.Dict[str, object], use_nested_query: bool = False, process_every_value: bool = False)

Bases: InstanceOperator

Casts specified fields to specified types.

Parameters:
  • use_nested_query (bool) – Whether to cast nested fields, expressed in dpath. Defaults to False.

  • fields (Dict[str, str]) – A dictionary mapping field names to the names of the types to cast the fields to. e.g: “int”, “str”, “float”, “bool”. Basic names of types

  • defaults (Dict[str, object]) – A dictionary mapping field names to default values for cases of casting failure.

  • process_every_value (bool) – If true, all fields involved must contain lists, and each value in the list is then casted. Defaults to False.

Examples

CastFields(

fields={“a/d”: “float”, “b”: “int”}, failure_defaults={“a/d”: 0.0, “b”: 0}, process_every_value=True, use_nested_query=True

)

would process the input instance: {“a”: {“d”: [“half”, “0.6”, 1, 12]}, “b”: [“2”]}

into {“a”: {“d”: [0.0, 0.6, 1.0, 12.0]}, “b”: [2]}

class unitxt.operators.ComputeExpressionMixin(__tags__: ~typing.Dict[str, str] = {}, data_classification_policy: ~typing.List[str] = None, expression: str, imports_list: ~typing.List[str] = [])

Bases: Artifact

Computes an expression expressed over fields of an instance.

Parameters:
  • expression (str) – the expression, in terms of names of fields of an instance

  • imports_list (List[str]) – list of names of imports needed for the evaluation of the expression

class unitxt.operators.CopyFields(__tags__: ~typing.Dict[str, str] = {}, data_classification_policy: ~typing.List[str] = None, caching: bool = None, apply_to_streams: ~typing.List[str] = None, dont_apply_to_streams: ~typing.List[str] = None, field: str | None = None, to_field: str | None = None, field_to_field: ~typing.List[~typing.List[str]] | ~typing.Dict[str, str] | None = None, use_query: bool, process_every_value: bool = False, get_default: ~typing.Any = None, not_exist_ok: bool = False)

Bases: FieldOperator

Copies values from specified fields to specified fields.

Args (of parent class):

field_to_field (Union[List[List], Dict[str, str]]): A list of lists, where each sublist contains the source field and the destination field, or a dictionary mapping source fields to destination fields.

Examples

An input instance {“a”: 2, “b”: 3}, when processed by CopyField(field_to_field={“a”: “b”} would yield {“a”: 2, “b”: 2}, and when processed by CopyField(field_to_field={“a”: “c”} would yield {“a”: 2, “b”: 3, “c”: 2}

with field names containing / , we can also copy inside the field: CopyFields(field_to_field={“a/0”: “a”}) would process instance {“a”: [1, 3]} into {“a”: 1}

class unitxt.operators.DeterministicBalancer(__tags__: ~typing.Dict[str, str] = {}, data_classification_policy: ~typing.List[str] = None, caching: bool = None, apply_to_streams: ~typing.List[str] | None = None, dont_apply_to_streams: ~typing.List[str] = None, max_instances: int = None, fields: ~typing.List[str])

Bases: StreamRefiner

A class used to balance streams deterministically.

For each instance, a signature is constructed from the values of the instance in specified input ‘fields’. By discarding instances from the input stream, DeterministicBalancer maintains equal number of instances for all signatures. When also input ‘max_instances’ is specified, DeterministicBalancer maintains a total instance count not exceeding ‘max_instances’. The total number of discarded instances is as few as possible.

fields

A list of field names to be used in producing the instance’s signature.

Type:

List[str]

max_instances
Type:

Optional, int

Usage:

balancer = DeterministicBalancer(fields=[“field1”, “field2”], max_instances=200) balanced_stream = balancer.process(stream)

Example

When input [{“a”: 1, “b”: 1},{“a”: 1, “b”: 2},{“a”: 2},{“a”: 3},{“a”: 4}] is fed into DeterministicBalancer(fields=[“a”]) the resulting stream will be: [{“a”: 1, “b”: 1},{“a”: 2},{“a”: 3},{“a”: 4}]

class unitxt.operators.DivideAllFieldsBy(__tags__: Dict[str, str] = {}, data_classification_policy: List[str] = None, caching: bool = None, apply_to_streams: List[str] = None, dont_apply_to_streams: List[str] = None, divisor: float = 1.0, strict: bool = False)

Bases: InstanceOperator

Recursively reach down to all fields that are float, and divide each by ‘divisor’.

The given instance is viewed as a tree whose internal nodes are dictionaries and lists, and the leaves are either ‘float’ and then divided, or other basic type, in which case, a ValueError is raised if input flag ‘strict’ is True, or – left alone, if ‘strict’ is False.

Parameters:
  • divisor (float) –

  • strict (bool) –

Example

when instance {“a”: 10.0, “b”: [2.0, 4.0, 7.0], “c”: 5} is processed by operator: operator = DivideAllFieldsBy(divisor=2.0) the output is: {“a”: 5.0, “b”: [1.0, 2.0, 3.5], “c”: 5} If the operator were defined with strict=True, through: operator = DivideAllFieldsBy(divisor=2.0, strict=True), the processing of the above instance would raise a ValueError, for the integer at “c”.

exception unitxt.operators.DownloadError(message)

Bases: Exception

class unitxt.operators.DownloadOperator(__tags__: ~typing.Dict[str, str] = {}, data_classification_policy: ~typing.List[str] = None, source: str, target: str)

Bases: SideEffectOperator

Operator for downloading a file from a given URL to a specified local path.

source

URL of the file to be downloaded.

Type:

str

target

Local path where the downloaded file should be saved.

Type:

str

class unitxt.operators.DuplicateInstances(__tags__: ~typing.Dict[str, str] = {}, data_classification_policy: ~typing.List[str] = None, caching: bool = None, apply_to_streams: ~typing.List[str] = None, dont_apply_to_streams: ~typing.List[str] = None, num_duplications: int, duplication_index_field: str | None = None)

Bases: StreamOperator

Operator which duplicates each instance in stream a given number of times.

num_duplications

How many times each instance should be duplicated (1 means no duplication).

Type:

int

duplication_index_field

If given, then additional field with specified name is added to each duplicated instance, which contains id of a given duplication. Defaults to None, so no field is added.

Type:

Optional[str]

class unitxt.operators.EncodeLabels(__tags__: ~typing.Dict[str, str] = {}, data_classification_policy: ~typing.List[str] = None, caching: bool = None, apply_to_streams: ~typing.List[str] = None, dont_apply_to_streams: ~typing.List[str] = None, fields: ~typing.List[str])

Bases: InstanceOperator

Encode each value encountered in any field in ‘fields’ into the integers 0,1,…

Encoding is determined by a str->int map that is built on the go, as different values are first encountered in the stream, either as list members or as values in single-value fields.

Parameters:

fields (List[str]) – The fields to encode together.

Example: applying

EncodeLabels(fields = [“a”, “b/*”]) on input stream = [{“a”: “red”, “b”: [“red”, “blue”], “c”:”bread”}, {“a”: “blue”, “b”: [“green”], “c”:”water”}] will yield the output stream = [{‘a’: 0, ‘b’: [0, 1], ‘c’: ‘bread’}, {‘a’: 1, ‘b’: [2], ‘c’: ‘water’}]

Note: qpath is applied here, and hence, fields that are lists, should be included in input ‘fields’ with the appendix “/*” as in the above example.

class unitxt.operators.ExecuteExpression(__tags__: ~typing.Dict[str, str] = {}, data_classification_policy: ~typing.List[str] = None, expression: str, imports_list: ~typing.List[str] = [], caching: bool = None, apply_to_streams: ~typing.List[str] = None, dont_apply_to_streams: ~typing.List[str] = None, to_field: str)

Bases: InstanceOperator, ComputeExpressionMixin

Compute an expression, specified as a string to be eval-uated, over the instance’s fields, and store the result in field to_field.

Raises an error if a field mentioned in the query is missing from the instance.

Parameters:
  • expression (str) – an expression to be evaluated over the fields of the instance

  • to_field (str) – the field where the result is to be stored into

  • imports_list (List[str]) – names of imports needed for the eval of the query (e.g. ‘re’, ‘json’)

Examples

When instance {“a”: 2, “b”: 3} is process-ed by operator ExecuteExpression(expression=”a+b”, to_field = “c”) the result is {“a”: 2, “b”: 3, “c”: 5}

When instance {“a”: “hello”, “b”: “world”} is process-ed by operator ExecuteExpression(expression = “a+’ ‘+b”, to_field = “c”) the result is {“a”: “hello”, “b”: “world”, “c”: “hello world”}

class unitxt.operators.ExtractFieldValues(__tags__: ~typing.Dict[str, str] = {}, data_classification_policy: ~typing.List[str] = None, caching: bool = None, field: str, stream_name: str, overall_top_frequency_percent: int | None = 100, min_frequency_percent: int | None = 0, to_field: str, process_every_value: bool | None = False)

Bases: ExtractMostCommonFieldValues

class unitxt.operators.ExtractMostCommonFieldValues(__tags__: ~typing.Dict[str, str] = {}, data_classification_policy: ~typing.List[str] = None, caching: bool = None, field: str, stream_name: str, overall_top_frequency_percent: int | None = 100, min_frequency_percent: int | None = 0, to_field: str, process_every_value: bool | None = False)

Bases: MultiStreamOperator

class unitxt.operators.ExtractZipFile(__tags__: ~typing.Dict[str, str] = {}, data_classification_policy: ~typing.List[str] = None, zip_file: str, target_dir: str)

Bases: SideEffectOperator

Operator for extracting files from a zip archive.

zip_file

Path of the zip file to be extracted.

Type:

str

target_dir

Directory where the contents of the zip file will be extracted.

Type:

str

class unitxt.operators.FeatureGroupedShuffle(__tags__: Dict[str, str] = {}, data_classification_policy: List[str] = None, caching: bool = None, apply_to_streams: List[str] = None, dont_apply_to_streams: List[str] = None, page_size: int = 1000, random_generator: Random = None, grouping_features: List[str] = None, shuffle_within_group: bool = False)

Bases: Shuffle

Class for shuffling an input dataset by instance ‘blocks’, not on the individual instance level.

Example is if the dataset consists of questions with paraphrases of it, and each question falls into a topic. All paraphrases have the same ID value as the original. In this case, we may want to shuffle on grouping_features = [‘question ID’], to keep the paraphrases and original question together. We may also want to group by both ‘question ID’ and ‘topic’, if the question IDs are repeated between topics. In this case, grouping_features = [‘question ID’, ‘topic’]

Parameters:
  • grouping_features (list of strings) – list of feature names to use to define the groups. a group is defined by each unique observed combination of data values for features in grouping_features

  • shuffle_within_group (bool) – whether to further shuffle the instances within each group block, keeping the block order

Args (of superclass):
page_size (int): The size of each page in the stream. Defaults to 1000.

Note: shuffle_by_grouping_features determines the unique groups (unique combinations of values of grouping_features) separately by page (determined by page_size). If a block of instances in the same group are split into separate pages (either by a page break falling in the group, or the dataset was not sorted by grouping_features), these instances will be shuffled separately and thus the grouping may be broken up by pages. If the user wants to ensure the shuffle does the grouping and shuffling across all pages, set the page_size to be larger than the dataset size. See outputs_2features_bigpage and outputs_2features_smallpage in test_grouped_shuffle.

class unitxt.operators.FieldOperator(__tags__: ~typing.Dict[str, str] = {}, data_classification_policy: ~typing.List[str] = None, caching: bool = None, apply_to_streams: ~typing.List[str] = None, dont_apply_to_streams: ~typing.List[str] = None, field: str | None = None, to_field: str | None = None, field_to_field: ~typing.List[~typing.List[str]] | ~typing.Dict[str, str] | None = None, use_query: bool, process_every_value: bool = False, get_default: ~typing.Any = None, not_exist_ok: bool = False)

Bases: InstanceFieldOperator

class unitxt.operators.FilterByCondition(__tags__: ~typing.Dict[str, str] = {}, data_classification_policy: ~typing.List[str] = None, caching: bool = None, apply_to_streams: ~typing.List[str] = None, dont_apply_to_streams: ~typing.List[str] = None, values: ~typing.Dict[str, ~typing.Any], condition: str, error_on_filtered_all: bool = True)

Bases: StreamOperator

Filters a stream, yielding only instances in which the values in required fields follow the required condition operator.

Raises an error if a required field name is missing from the input instance.

Parameters:
  • values (Dict[str, Any]) – Field names and respective Values that instances must match according the condition, to be included in the output.

  • condition – the name of the desired condition operator between the specified (sub) field’s value and the provided constant value. Supported conditions are (“gt”, “ge”, “lt”, “le”, “ne”, “eq”, “in”,”not in”)

  • error_on_filtered_all (bool, optional) – If True, raises an error if all instances are filtered out. Defaults to True.

Examples

FilterByCondition(values = {“a”:4}, condition = “gt”) will yield only instances where field “a” contains a value > 4 FilterByCondition(values = {“a”:4}, condition = “le”) will yield only instances where “a”<=4 FilterByCondition(values = {“a”:[4,8]}, condition = “in”) will yield only instances where “a” is 4 or 8 FilterByCondition(values = {“a”:[4,8]}, condition = “not in”) will yield only instances where “a” different from 4 or 8 FilterByCondition(values = {“a/b”:[4,8]}, condition = “not in”) will yield only instances where “a” is

a dict in which key “b” is mapped to a value that is neither 4 nor 8

FilterByCondition(values = {“a[2]”:4}, condition = “le”) will yield only instances where “a” is a list whose 3-rd

element is <= 4

condition_to_func = {'eq': <built-in function eq>, 'ge': <built-in function ge>, 'gt': <built-in function gt>, 'in': None, 'le': <built-in function le>, 'lt': <built-in function lt>, 'ne': <built-in function ne>, 'not in': None}
class unitxt.operators.FilterByExpression(__tags__: ~typing.Dict[str, str] = {}, data_classification_policy: ~typing.List[str] = None, expression: str, imports_list: ~typing.List[str] = [], caching: bool = None, apply_to_streams: ~typing.List[str] = None, dont_apply_to_streams: ~typing.List[str] = None, error_on_filtered_all: bool = True)

Bases: StreamOperator, ComputeExpressionMixin

Filters a stream, yielding only instances which fulfil a condition specified as a string to be python’s eval-uated.

Raises an error if a field participating in the specified condition is missing from the instance

Parameters:
  • expression (str) – a condition over fields of the instance, to be processed by python’s eval()

  • imports_list (List[str]) – names of imports needed for the eval of the query (e.g. ‘re’, ‘json’)

  • error_on_filtered_all (bool, optional) – If True, raises an error if all instances are filtered out. Defaults to True.

Examples

FilterByExpression(expression = “a > 4”) will yield only instances where “a”>4 FilterByExpression(expression = “a <= 4 and b > 5”) will yield only instances where the value of field “a” is not exceeding 4 and in field “b” – greater than 5 FilterByExpression(expression = “a in [4, 8]”) will yield only instances where “a” is 4 or 8 FilterByExpression(expression = “a not in [4, 8]”) will yield only instances where “a” is neither 4 nor 8 FilterByExpression(expression = “a[‘b’] not in [4, 8]”) will yield only instances where “a” is a dict in which key ‘b’ is mapped to a value that is neither 4 nor 8

class unitxt.operators.FlattenInstances(__tags__: Dict[str, str] = {}, data_classification_policy: List[str] = None, caching: bool = None, apply_to_streams: List[str] = None, dont_apply_to_streams: List[str] = None, parent_key: str = '', sep: str = '_')

Bases: InstanceOperator

Flattens each instance in a stream, making nested dictionary entries into top-level entries.

Parameters:
  • parent_key (str) – A prefix to use for the flattened keys. Defaults to an empty string.

  • sep (str) – The separator to use when concatenating nested keys. Defaults to “_”.

class unitxt.operators.FromIterables(__tags__: Dict[str, str] = {}, data_classification_policy: List[str] = None, caching: bool = None)

Bases: StreamInitializerOperator

Creates a MultiStream from a dict of named iterables.

Example

operator = FromIterables() ms = operator.process(iterables)

class unitxt.operators.GetItemByIndex(__tags__: ~typing.Dict[str, str] = {}, data_classification_policy: ~typing.List[str] = None, caching: bool = None, apply_to_streams: ~typing.List[str] = None, dont_apply_to_streams: ~typing.List[str] = None, field: str | None = None, to_field: str | None = None, field_to_field: ~typing.List[~typing.List[str]] | ~typing.Dict[str, str] | None = None, use_query: bool, process_every_value: bool = False, get_default: ~typing.Any = None, not_exist_ok: bool = False, items_list: ~typing.List[~typing.Any])

Bases: FieldOperator

Get from the item list by the index in the field.

class unitxt.operators.IndexOf(__tags__: ~typing.Dict[str, str] = {}, data_classification_policy: ~typing.List[str] = None, caching: bool = None, apply_to_streams: ~typing.List[str] = None, dont_apply_to_streams: ~typing.List[str] = None, search_in: str, index_of: str, to_field: str, use_query: bool)

Bases: InstanceOperator

For a given instance, finds the offset of value of field ‘index_of’, within the value of field ‘search_in’.

class unitxt.operators.InstanceFieldOperator(__tags__: ~typing.Dict[str, str] = {}, data_classification_policy: ~typing.List[str] = None, caching: bool = None, apply_to_streams: ~typing.List[str] = None, dont_apply_to_streams: ~typing.List[str] = None, field: str | None = None, to_field: str | None = None, field_to_field: ~typing.List[~typing.List[str]] | ~typing.Dict[str, str] | None = None, use_query: bool, process_every_value: bool = False, get_default: ~typing.Any = None, not_exist_ok: bool = False)

Bases: InstanceOperator

A general stream instance operator that processes the values of a field (or multiple ones).

Parameters:
  • field (Optional[str]) – The field to process, if only a single one is passed. Defaults to None

  • to_field (Optional[str]) – Field name to save result into, if only one field is processed, if None is passed the operation would happen in-place and its result would replace the value of “field”. Defaults to None

  • field_to_field (Optional[Union[List[List[str]], Dict[str, str]]]) – Mapping from names of fields to process, to names of fields to save the results into. Inner List, if used, should be of length 2. A field is processed by feeding its value into method ‘process_value’ and storing the result in to_field that is mapped to the field. When the type of argument ‘field_to_field’ is List, the order by which the fields are processed is their order in the (outer) List. But when the type of argument ‘field_to_field’ is Dict, there is no uniquely determined order. The end result might depend on that order if either (1) two different fields are mapped to the same to_field, or (2) a field shows both as a key and as a value in different mappings. The operator throws an AssertionError in either of these cases. field_to_field defaults to None

  • process_every_value (bool) – Processes the values in a list instead of the list as a value, similar to *var. Defaults to False

  • Note – if ‘field’ and ‘to_field’ (or both members of a pair in ‘field_to_field’) are equal (or share a common

  • /) (prefix if 'field' and 'to_field' contain a) –

  • 'field' (then the result of the operation is saved within) –

class unitxt.operators.InterleaveListsToDialogOperator(__tags__: ~typing.Dict[str, str] = {}, data_classification_policy: ~typing.List[str] = None, caching: bool = None, apply_to_streams: ~typing.List[str] = None, dont_apply_to_streams: ~typing.List[str] = None, user_turns_field: str, assistant_turns_field: str, user_role_label: str = 'user', assistant_role_label: str = 'assistant', to_field: str)

Bases: InstanceOperator

Interleaves two lists, one of user dialog turns and one of assistant dialog turns, into a single list of tuples, alternating between “user” and “assistant”.

The list of tuples if of format (role, turn_content), where the role label is specified by the ‘user_role_label’ and ‘assistant_role_label’ fields (default to “user” and “assistant”).

The user turns and assistant turns field are specified in the arguments.

The value of each of the ‘fields’ is assumed to be a list.

class unitxt.operators.Intersect(__tags__: ~typing.Dict[str, str] = {}, data_classification_policy: ~typing.List[str] = None, caching: bool = None, apply_to_streams: ~typing.List[str] = None, dont_apply_to_streams: ~typing.List[str] = None, field: str | None = None, to_field: str | None = None, field_to_field: ~typing.List[~typing.List[str]] | ~typing.Dict[str, str] | None = None, use_query: bool, process_every_value: bool = False, get_default: ~typing.Any = None, not_exist_ok: bool = False, allowed_values: ~typing.List[~typing.Any])

Bases: FieldOperator

Intersects the value of a field, which must be a list, with a given list.

Parameters:

allowed_values (list) –

class unitxt.operators.IterableSource(__tags__: ~typing.Dict[str, str] = {}, data_classification_policy: ~typing.List[str] = None, caching: bool = None, iterables: ~typing.Dict[str, ~typing.Iterable])

Bases: SourceOperator

Creates a MultiStream from a dict of named iterables.

It is a callable.

Parameters:

iterables (Dict[str, Iterable]) – A dictionary mapping stream names to iterables.

Example

operator = IterableSource(input_dict) ms = operator()

class unitxt.operators.JoinStr(__tags__: ~typing.Dict[str, str] = {}, data_classification_policy: ~typing.List[str] = None, caching: bool = None, apply_to_streams: ~typing.List[str] = None, dont_apply_to_streams: ~typing.List[str] = None, field: str | None = None, to_field: str | None = None, field_to_field: ~typing.List[~typing.List[str]] | ~typing.Dict[str, str] | None = None, use_query: bool, process_every_value: bool = False, get_default: ~typing.Any = None, not_exist_ok: bool = False, separator: str = ', ')

Bases: FieldOperator

Joins a list of strings (contents of a field), similar to str.join().

Parameters:

separator (str) – text to put between values

class unitxt.operators.LengthBalancer(__tags__: ~typing.Dict[str, str] = {}, data_classification_policy: ~typing.List[str] = None, caching: bool = None, apply_to_streams: ~typing.List[str] | None = None, dont_apply_to_streams: ~typing.List[str] = None, max_instances: int = None, fields: ~typing.List[str] | None, segments_boundaries: ~typing.List[int])

Bases: DeterministicBalancer

Balances by a signature that reflects the total length of the fields’ values, quantized into integer segments.

Parameters:
  • segments_boundaries (List[int]) – distinct integers sorted in increasing order, that maps a given total length

  • index (into the index of the least of them that exceeds the total length. (If none exceeds -- into one) –

  • beyond

  • namely

  • segments_boundaries) (the length of) –

  • fields (Optional, List[str]) –

Example

when input [{“a”: [1, 3], “b”: 0, “id”: 0}, {“a”: [1, 3], “b”: 0, “id”: 1}, {“a”: [], “b”: “a”, “id”: 2}] is fed into

LengthBalancer(fields=["a"], segments_boundaries=[1])

input instances will be counted and balanced against two categories: empty total length (less than 1), and non-empty.

class unitxt.operators.ListFieldValues(__tags__: ~typing.Dict[str, str] = {}, data_classification_policy: ~typing.List[str] = None, caching: bool = None, apply_to_streams: ~typing.List[str] = None, dont_apply_to_streams: ~typing.List[str] = None, fields: ~typing.List[str], to_field: str, use_query: bool)

Bases: InstanceOperator

Concatenates values of multiple fields into a list, and assigns it to a new field.

class unitxt.operators.MapInstanceValues(__tags__: ~typing.Dict[str, str] = {}, data_classification_policy: ~typing.List[str] = None, caching: bool = None, apply_to_streams: ~typing.List[str] = None, dont_apply_to_streams: ~typing.List[str] = None, mappers: ~typing.Dict[str, ~typing.Dict[str, str]], strict: bool = True, process_every_value: bool = False)

Bases: InstanceOperator

A class used to map instance values into other values.

This class is a type of InstanceOperator, it maps values of instances in a stream using predefined mappers.

mappers

The mappers to use for mapping instance values. Keys are the names of the fields to be mapped, and values are dictionaries that define the mapping from old values to new values.

Type:

Dict[str, Dict[str, str]]

strict

If True, the mapping is applied strictly. That means if a value does not exist in the mapper, it will raise a KeyError. If False, values that are not present in the mapper are kept as they are.

Type:

bool

process_every_value

If True, all fields to be mapped should be lists, and the mapping is to be applied to their individual elements. If False, mapping is only applied to a field containing a single value.

Type:

bool

Examples

MapInstanceValues(mappers={“a”: {“1”: “hi”, “2”: “bye”}}) replaces ‘1’ with ‘hi’ and ‘2’ with ‘bye’ in field ‘a’ in all instances of all streams: instance {“a”:”1”, “b”: 2} becomes {“a”:”hi”, “b”: 2}.

MapInstanceValues(mappers={“a”: {“1”: “hi”, “2”: “bye”}}, process_every_value=True) Assuming field ‘a’ is a list of values, potentially including “1”-s and “2”-s, this replaces each such “1” with “hi” and “2” – with “bye” in all instances of all streams: instance {“a”: [“1”, “2”], “b”: 2} becomes {“a”: [“hi”, “bye”], “b”: 2}.

MapInstanceValues(mappers={“a”: {“1”: “hi”, “2”: “bye”}}, strict=True) To ensure that all values of field ‘a’ are mapped in every instance, use strict=True. Input instance {“a”:”3”, “b”: 2} will raise an exception per the above call, because “3” is not a key in the mapper of “a”.

MapInstanceValues(mappers={“a”: {str([1,2,3,4]): ‘All’, str([]): ‘None’}}, strict=True) replaces a list [1,2,3,4] with the string ‘All’ and an empty list by string ‘None’. Note that mapped values are defined by their string representation, so mapped values must be converted to strings.

class unitxt.operators.MergeStreams(__tags__: Dict[str, str] = {}, data_classification_policy: List[str] = None, caching: bool = None, streams_to_merge: List[str] = None, new_stream_name: str = 'all', add_origin_stream_name: bool = True, origin_stream_name_field_name: str = 'origin')

Bases: MultiStreamOperator

Merges multiple streams into a single stream.

Parameters:
  • new_stream_name (str) – The name of the new stream resulting from the merge.

  • add_origin_stream_name (bool) – Whether to add the origin stream name to each instance.

  • origin_stream_name_field_name (str) – The field name for the origin stream name.

class unitxt.operators.MinimumOneExamplePerLabelRefiner(__tags__: ~typing.Dict[str, str] = {}, data_classification_policy: ~typing.List[str] = None, caching: bool = None, apply_to_streams: ~typing.List[str] | None = None, dont_apply_to_streams: ~typing.List[str] = None, max_instances: int = None, fields: ~typing.List[str])

Bases: StreamRefiner

A class used to return a specified number instances ensuring at least one example per label.

For each instance, a signature value is constructed from the values of the instance in specified input ‘fields’. MinimumOneExamplePerLabelRefiner takes first instance that appears from each label (each unique signature), and then adds more elements up to the max_instances limit. In general, the refiner takes the first elements in the stream that meet the required conditions. MinimumOneExamplePerLabelRefiner then shuffles the results to avoid having one instance from each class first and then the rest . If max instance is not set, the original stream will be used

fields

A list of field names to be used in producing the instance’s signature.

Type:

List[str]

max_instances

Number of elements to select. Note that max_instances of StreamRefiners that are passed to the recipe (e.g. ‘train_refiner’. test_refiner) are overridden by the recipe parameters ( max_train_instances, max_test_instances)

Type:

Optional, int

Usage:

balancer = MinimumOneExamplePerLabelRefiner(fields=[“field1”, “field2”], max_instances=200) balanced_stream = balancer.process(stream)

Example

When input [{“a”: 1, “b”: 1},{“a”: 1, “b”: 2},{“a”: 1, “b”: 3},{“a”: 1, “b”: 4},{“a”: 2, “b”: 5}] is fed into MinimumOneExamplePerLabelRefiner(fields=[“a”], max_instances=3) the resulting stream will be: [{‘a’: 1, ‘b’: 1}, {‘a’: 1, ‘b’: 2}, {‘a’: 2, ‘b’: 5}] (order may be different)

class unitxt.operators.NullAugmentor(__tags__: Dict[str, str] = {}, data_classification_policy: List[str] = None, caching: bool = None, apply_to_streams: List[str] = None, dont_apply_to_streams: List[str] = None, augment_task_input: bool = False, augment_model_input: bool = False)

Bases: Augmentor

Does not change the input string.

class unitxt.operators.Perturb(__tags__: ~typing.Dict[str, str] = {}, data_classification_policy: ~typing.List[str] = None, caching: bool = None, apply_to_streams: ~typing.List[str] = None, dont_apply_to_streams: ~typing.List[str] = None, field: str | None = None, to_field: str | None = None, field_to_field: ~typing.List[~typing.List[str]] | ~typing.Dict[str, str] | None = None, use_query: bool, process_every_value: bool = False, get_default: ~typing.Any = None, not_exist_ok: bool = False, select_from: ~typing.List[~typing.Any] = [], percentage_to_perturb: int = 1)

Bases: FieldOperator

Slightly perturbs the contents of ‘field’. Could be Handy for imitating prediction from given target.

When task was classification, argument ‘select_from’ can be used to list the other potential classes, as a relevant perturbation

select_from: List[Any] = []
class unitxt.operators.RemoveFields(__tags__: ~typing.Dict[str, str] = {}, data_classification_policy: ~typing.List[str] = None, caching: bool = None, apply_to_streams: ~typing.List[str] = None, dont_apply_to_streams: ~typing.List[str] = None, fields: ~typing.List[str])

Bases: InstanceOperator

Remove specified fields from each instance in a stream.

Parameters:

fields (List[str]) – The fields to remove from each instance.

class unitxt.operators.RemoveValues(__tags__: ~typing.Dict[str, str] = {}, data_classification_policy: ~typing.List[str] = None, caching: bool = None, apply_to_streams: ~typing.List[str] = None, dont_apply_to_streams: ~typing.List[str] = None, field: str | None = None, to_field: str | None = None, field_to_field: ~typing.List[~typing.List[str]] | ~typing.Dict[str, str] | None = None, use_query: bool, process_every_value: bool = False, get_default: ~typing.Any = None, not_exist_ok: bool = False, unallowed_values: ~typing.List[~typing.Any])

Bases: FieldOperator

Removes elements in a field, which must be a list, using a given list of unallowed.

Parameters:

unallowed_values (list) –

class unitxt.operators.RenameFields(__tags__: ~typing.Dict[str, str] = {}, data_classification_policy: ~typing.List[str] = None, caching: bool = None, apply_to_streams: ~typing.List[str] = None, dont_apply_to_streams: ~typing.List[str] = None, field: str | None = None, to_field: str | None = None, field_to_field: ~typing.List[~typing.List[str]] | ~typing.Dict[str, str] | None = None, use_query: bool, process_every_value: bool = False, get_default: ~typing.Any = None, not_exist_ok: bool = False)

Bases: FieldOperator

Renames fields.

Move value from one field to another, potentially, if field name contains a /, from one branch into another. Remove the from field, potentially part of it in case of / in from_field.

Examples

RenameFields(field_to_field={“b”: “c”}) will change inputs [{“a”: 1, “b”: 2}, {“a”: 2, “b”: 3}] to [{“a”: 1, “c”: 2}, {“a”: 2, “c”: 3}]

RenameFields(field_to_field={“b”: “c/d”}) will change inputs [{“a”: 1, “b”: 2}, {“a”: 2, “b”: 3}] to [{“a”: 1, “c”: {“d”: 2}}, {“a”: 2, “c”: {“d”: 3}}]

RenameFields(field_to_field={“b”: “b/d”}) will change inputs [{“a”: 1, “b”: 2}, {“a”: 2, “b”: 3}] to [{“a”: 1, “b”: {“d”: 2}}, {“a”: 2, “b”: {“d”: 3}}]

RenameFields(field_to_field={“b/c/e”: “b/d”}) will change inputs [{“a”: 1, “b”: {“c”: {“e”: 2, “f”: 20}}}] to [{“a”: 1, “b”: {“c”: {“f”: 20}, “d”: 2}}]

class unitxt.operators.Shuffle(__tags__: Dict[str, str] = {}, data_classification_policy: List[str] = None, caching: bool = None, apply_to_streams: List[str] = None, dont_apply_to_streams: List[str] = None, page_size: int = 1000, random_generator: Random = None)

Bases: PagedStreamOperator

Shuffles the order of instances in each page of a stream.

Args (of superclass):

page_size (int): The size of each page in the stream. Defaults to 1000.

class unitxt.operators.ShuffleFieldValues(__tags__: ~typing.Dict[str, str] = {}, data_classification_policy: ~typing.List[str] = None, caching: bool = None, apply_to_streams: ~typing.List[str] = None, dont_apply_to_streams: ~typing.List[str] = None, field: str | None = None, to_field: str | None = None, field_to_field: ~typing.List[~typing.List[str]] | ~typing.Dict[str, str] | None = None, use_query: bool, process_every_value: bool = False, get_default: ~typing.Any = None, not_exist_ok: bool = False)

Bases: FieldOperator

Shuffles a list of values found in a field.

class unitxt.operators.SplitByNestedGroup(__tags__: Dict[str, str] = {}, data_classification_policy: List[str] = None, caching: bool = None, field_name_of_group: str = 'group', number_of_fusion_generations: int = 1)

Bases: MultiStreamOperator

Splits a MultiStream that is small - for metrics, hence: whole stream can sit in memory, split by the value of field ‘group’.

Parameters:

number_of_fusion_generations – int

the value in field group is of the form “sourcen/sourcenminus1/…” describing the sources in which the instance sat when these were fused, potentially several phases of fusion. the name of the most recent source sits first in this value. (See BaseFusion and its extensions) number_of_fuaion_generations specifies the length of the prefix by which to split the stream. E.g. for number_of_fusion_generations = 1, only the most recent fusion in creating this multi_stream, affects the splitting. For number_of_fusion_generations = -1, take the whole history written in this field, ignoring number of generations.

class unitxt.operators.SplitByValue(__tags__: ~typing.Dict[str, str] = {}, data_classification_policy: ~typing.List[str] = None, caching: bool = None, fields: ~typing.List[str])

Bases: MultiStreamOperator

Splits a MultiStream into multiple streams based on unique values in specified fields.

Parameters:

fields (List[str]) – The fields to use when splitting the MultiStream.

class unitxt.operators.StreamRefiner(__tags__: Dict[str, str] = {}, data_classification_policy: List[str] = None, caching: bool = None, apply_to_streams: List[str] | None = None, dont_apply_to_streams: List[str] = None, max_instances: int = None)

Bases: StreamOperator

Discard from the input stream all instances beyond the leading ‘max_instances’ instances.

Thereby, if the input stream consists of no more than ‘max_instances’ instances, the resulting stream is the whole of the input stream. And if the input stream consists of more than ‘max_instances’ instances, the resulting stream only consists of the leading ‘max_instances’ of the input stream.

Args: max_instances (int)

apply_to_streams (optional, list(str)): names of streams to refine.

Examples

when input = [{“a”: 1},{“a”: 2},{“a”: 3},{“a”: 4},{“a”: 5},{“a”: 6}] is fed into StreamRefiner(max_instances=4) the resulting stream is [{“a”: 1},{“a”: 2},{“a”: 3},{“a”: 4}]

class unitxt.operators.TakeByField(__tags__: ~typing.Dict[str, str] = {}, data_classification_policy: ~typing.List[str] = None, caching: bool = None, apply_to_streams: ~typing.List[str] = None, dont_apply_to_streams: ~typing.List[str] = None, field: str, index: str, to_field: str = None, use_query: bool)

Bases: InstanceOperator

From field ‘field’ of a given instance, select the member indexed by field ‘index’, and store to field ‘to_field’.

exception unitxt.operators.UnexpectedHttpCodeError(http_code)

Bases: Exception

class unitxt.operators.Unique(__tags__: ~typing.Dict[str, str] = {}, data_classification_policy: ~typing.List[str] = None, fields: ~typing.List[str])

Bases: SingleStreamReducer

Reduces a stream to unique instances based on specified fields.

Parameters:

fields (List[str]) – The fields that should be unique in each instance.

class unitxt.operators.ZipFieldValues(__tags__: ~typing.Dict[str, str] = {}, data_classification_policy: ~typing.List[str] = None, caching: bool = None, apply_to_streams: ~typing.List[str] = None, dont_apply_to_streams: ~typing.List[str] = None, fields: ~typing.List[str], to_field: str, longest: bool = False, use_query: bool)

Bases: InstanceOperator

Zips values of multiple fields in a given instance, similar to list(zip(*fields)).

The value in each of the specified ‘fields’ is assumed to be a list. The lists from all ‘fields’ are zipped, and stored into ‘to_field’.

If ‘longest’=False, the length of the zipped result is determined by the shortest input value. If ‘longest’=False, the length of the zipped result is determined by the longest input, padding shorter inputs with None -s.