Upload folder using huggingface_hub
Browse filesFiles changed (30)
- api.py+49-5
- artifact.py+28-18
- collections_operators.py+60-2
- data.py+1-1
- dataclass.py+59
- dialog_operators.py+10-1
- dict_utils.py+1-1
- error_utils.py+254-12
- evaluate_cli.py+56-3
- formats.py+53-9
- fusion.py+14-16
- inference.py+229-126
- llm_as_judge_constants.py+1-2
- loaders.py+107-81
- metric.py+1-1
- metric_utils.py+19-12
- metrics.py+548-654
- operator.py+23-13
- operators.py+79-58
- processors.py+11-1
- schema.py+1-1
- serializers.py+18-2
- settings_utils.py+4
- struct_data_operators.py+49
- task.py+13-8
- templates.py+13-1
- sql_utils.py → text2sql_utils.pyRenamed+488-2
- type_utils.py+18-2
- types.py+56-26
- version.py+1-1
10 unmodified lines111213141516132 unmodified lines1491501511521531542 unmodified lines15715815916016116216316416516616716816917017117217317417517617717810 unmodified linesfrom .artifact import fetch_artifactfrom .benchmark import Benchmarkfrom .card import TaskCardfrom .dataset_utils import get_dataset_artifactfrom .error_utils import UnitxtErrorfrom .inference import (132 unmodified linesreturn load_dataset(card=card, split=split, **kwargs)def _source_to_dataset(source: SourceOperator,split=None,2 unmodified lines):from .dataset import Dataset as UnitxtDatasetstream = source()try:ds_builder = UnitxtDataset(dataset_name="unitxt",config_name="recipe-" + short_hex_hash(repr(source)),version=constants.version,)if split is not None:stream = {split: stream[split]}ds_builder._generators = streamds_builder.download_and_prepare(verification_mode="no_checks",download_mode=None if use_cache else "force_redownload",)if streaming:return ds_builder.as_streaming_dataset(split=split)10 unmodified lines11121314151617132 unmodified lines1501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841852 unmodified lines18818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122210 unmodified linesfrom .artifact import fetch_artifactfrom .benchmark import Benchmarkfrom .card import TaskCardfrom .dataclass import to_dictfrom .dataset_utils import get_dataset_artifactfrom .error_utils import UnitxtErrorfrom .inference import (132 unmodified linesreturn load_dataset(card=card, split=split, **kwargs)def object_to_str_without_addresses(obj):"""Generates a string representation of a Python object while removing memory address references.This function is useful for creating consistent and comparable string representations of objectsthat would otherwise include memory addresses (e.g., `<object_name at 0x123abc>`), which can varybetween executions. By stripping the memory address, the function ensures that the representationis stable and independent of the object's location in memory.Args:obj: Any Python object to be converted to a string representation.Returns:str: A string representation of the object with memory addresses removed if present.Example:```pythonclass MyClass:passobj = MyClass()print(str(obj)) # "<__main__.MyClass object at 0x7f8b9d4d6e20>"print(to_str_without_addresses(obj)) # "<__main__.MyClass object>"```"""obj_str = str(obj)if " at 0x" in obj_str:obj_str = obj_str.split(" at 0x")[0] + ">"return obj_strdef _source_to_dataset(source: SourceOperator,split=None,2 unmodified lines):from .dataset import Dataset as UnitxtDataset# Generate a unique signature for the sourcesource_signature = json.dumps(to_dict(source, object_to_str_without_addresses), sort_keys=True)config_name = "recipe-" + short_hex_hash(source_signature)# Obtain data stream from the sourcestream = source()try:ds_builder = UnitxtDataset(dataset_name="unitxt",config_name=config_name, # Dictate the cache nameversion=constants.version,)if split is not None:stream = {split: stream[split]}ds_builder._generators = streamtry:ds_builder.download_and_prepare(verification_mode="no_checks",download_mode=None if use_cache else "force_redownload",)except DatasetGenerationError as e:if e.__cause__:raise e.__cause__ from Noneif e.__context__:raise e.__context__ from Noneraiseif streaming:return ds_builder.as_streaming_dataset(split=split)
15 unmodified lines16171819202122232425262728313 unmodified lines34234334434534634734834917 unmodified lines36736836937037137237337437537637771 unmodified lines44945045145245345445545645745845946046146246346446546646746815 unmodified linesNonPositionalField,fields,)from .error_utils import Documentation, UnitxtError, UnitxtWarningfrom .logging_utils import get_loggerfrom .parsing_utils import (separate_inside_and_outside_square_brackets,)from .settings_utils import get_constants, get_settingsfrom .text_utils import camel_to_snake_case, is_camel_case, print_dict_as_yamlfrom .type_utils import isoftype, issubtypefrom .utils import (artifacts_json_cache,313 unmodified linesself.verify_data_classification_policy()self.prepare_args()if not settings.skip_artifacts_prepare_and_verify:self.prepare()self.verify()def _to_raw_dict(self):return {17 unmodified linesdef to_json(self):data = self.to_dict()return json_dump(data)def to_yaml(self):data = self.to_dict()return print_dict_as_yaml(data)def serialize(self):if self.__id__ is not None:71 unmodified lines)return instanceif not any(data_classification in data_classification_policyfor data_classification in instance_data_classification):raise UnitxtError(f"The instance '{instance} 'has the following data classification policy "f"'{instance_data_classification}', however, the artifact '{name}' "f"is only configured to support the data with classification "f"'{data_classification_policy}'. To enable this either change "f"the 'data_classification_policy' attribute of the artifact, "f"or modify the environment variable "f"'UNITXT_DATA_CLASSIFICATION_POLICY' accordingly.",Documentation.DATA_CLASSIFICATION_POLICY,)return instance15 unmodified lines16171819202122232425262728313 unmodified lines34234334434534634734834935035117 unmodified lines36937037137237337437537637737837938038138271 unmodified lines45445545645745845946046146246346446546646746846947047147247347447547647747815 unmodified linesNonPositionalField,fields,)from .error_utils import Documentation, UnitxtError, UnitxtWarning, error_contextfrom .logging_utils import get_loggerfrom .parsing_utils import (separate_inside_and_outside_square_brackets,)from .settings_utils import get_constants, get_settingsfrom .text_utils import camel_to_snake_case, is_camel_casefrom .type_utils import isoftype, issubtypefrom .utils import (artifacts_json_cache,313 unmodified linesself.verify_data_classification_policy()self.prepare_args()if not settings.skip_artifacts_prepare_and_verify:with error_context(self, action="Prepare Object"):self.prepare()with error_context(self, action="Verify Object"):self.verify()def _to_raw_dict(self):return {17 unmodified linesdef to_json(self):data = self.to_dict()return json_dump(data)def to_yaml(self):import yamldata = self.to_dict()return yaml.dump(data)def serialize(self):if self.__id__ is not None:71 unmodified lines)return instancewith error_context(self,action="Sensitive Data Verification",help="https://www.unitxt.ai/en/latest/docs/data_classification_policy.html",):if not any(data_classification in data_classification_policyfor data_classification in instance_data_classification):raise UnitxtError(f"The instance '{instance} 'has the following data classification policy "f"'{instance_data_classification}', however, the artifact '{name}' "f"is only configured to support the data with classification "f"'{data_classification_policy}'. To enable this either change "f"the 'data_classification_policy' attribute of the artifact, "f"or modify the environment variable "f"'UNITXT_DATA_CLASSIFICATION_POLICY' accordingly.",Documentation.DATA_CLASSIFICATION_POLICY,)return instance
1234566 unmodified lines131415161718192021222340 unmodified lines64656667686921 unmodified lines9192939495969798991001011026 unmodified lines109110111112113114from typing import Any, Dict, Generator, List, Optionalfrom .dict_utils import dict_get, dict_setfrom .operators import FieldOperator, StreamOperatorfrom .stream import Streamfrom .utils import recursive_shallow_copy6 unmodified linesreturn dict(zip(self.with_keys, tup))class DictToTuplesList(FieldOperator):def process_value(self, dic: Dict) -> Any:return list(dic.items())class Wrap(FieldOperator):inside: str40 unmodified linesreturn collection[self.item]class DuplicateByList(StreamOperator):field: strto_field: Optional[str] = None21 unmodified linesfield: strto_field: Optional[str] = Noneuse_deep_copy: bool = Falsedef process(self, stream: Stream, stream_name: Optional[str] = None) -> Generator:to_field = self.field if self.to_field is None else self.to_fieldfor instance in stream:elements = instance[self.field]for i in range(1, len(elements) + 1):if self.use_deep_copy:instance_copy = recursive_shallow_copy(instance)instance_copy[to_field] = elements[:i]6 unmodified linesyield instance_copyclass GetLength(FieldOperator):def process_value(self, collection: Any) -> Any:return len(collection)123456786 unmodified lines1516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656640 unmodified lines10710810911011111211311411511611711811921 unmodified lines1411421431441451461471481491501511521531541551566 unmodified lines163164165166167168169170171172from itertools import zip_longestfrom typing import Any, Dict, Generator, List, Optionalfrom .dict_utils import dict_get, dict_setfrom .operator import InstanceOperatorfrom .operators import FieldOperator, StreamOperatorfrom .stream import Streamfrom .utils import recursive_shallow_copy6 unmodified linesreturn dict(zip(self.with_keys, tup))class Zip(InstanceOperator):fields: List[str]to_field: strdef zip(self, values):return list(zip(*values))def process(self, instance: Dict[str, Any], stream_name: Optional[str] = None) -> Dict[str, Any]:values = []for field in self.fields:values.append(dict_get(instance, field))dict_set(instance, self.to_field, self.zip(values))return instanceclass ZipLongest(Zip):fields: List[str]fill_value: Any = Nonedef zip(self, values):return list(zip_longest(*values, fillvalue=self.fill_value))class DictToTuplesList(FieldOperator):def process_value(self, dic: Dict) -> Any:return list(dic.items())def flatten(container):def _flat_gen(x):for item in x:if isinstance(item, (list, tuple)):yield from _flat_gen(item)else:yield itemreturn type(container)(_flat_gen(container))class Flatten(FieldOperator):def process_value(self, value: Any) -> Any:return flatten(value)class Wrap(FieldOperator):inside: str40 unmodified linesreturn collection[self.item]class Pop(FieldOperator):item: Any = Nonedef process_value(self, collection: Any) -> Any:return collection.pop(self.item)class DuplicateByList(StreamOperator):field: strto_field: Optional[str] = None21 unmodified linesfield: strto_field: Optional[str] = Noneuse_deep_copy: bool = Falsestart: int = 1end: int = 0step: int = 1def process(self, stream: Stream, stream_name: Optional[str] = None) -> Generator:to_field = self.field if self.to_field is None else self.to_fieldfor instance in stream:elements = dict_get(instance, self.field)end = len(elements) + 1 + self.endfor i in range(self.start, end, self.step):if self.use_deep_copy:instance_copy = recursive_shallow_copy(instance)instance_copy[to_field] = elements[:i]6 unmodified linesyield instance_copyclass ExplodeSubLists(DuplicateBySubLists):passclass GetLength(FieldOperator):def process_value(self, collection: Any) -> Any:return len(collection)
58 unmodified lines596061626364652 unmodified lines68697071727358 unmodified linesfrom .span_lableing_operators import __file__ as _from .split_utils import __file__ as _from .splitters import __file__ as _from .sql_utils import __file__ as _from .standard import __file__ as _from .stream import __file__ as _from .stream_operators import __file__ as _2 unmodified linesfrom .system_prompts import __file__ as _from .task import __file__ as _from .templates import __file__ as _from .text_utils import __file__ as _from .type_utils import __file__ as _from .types import __file__ as _58 unmodified lines5960616263642 unmodified lines6768697071727358 unmodified linesfrom .span_lableing_operators import __file__ as _from .split_utils import __file__ as _from .splitters import __file__ as _from .standard import __file__ as _from .stream import __file__ as _from .stream_operators import __file__ as _2 unmodified linesfrom .system_prompts import __file__ as _from .task import __file__ as _from .templates import __file__ as _from .text2sql_utils import __file__ as _from .text_utils import __file__ as _from .type_utils import __file__ as _from .types import __file__ as _
296 unmodified lines297298299300301302296 unmodified linesreturn copy.deepcopy(obj)class DataclassMeta(ABCMeta):"""Metaclass for Dataclass.296 unmodified lines297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361296 unmodified linesreturn copy.deepcopy(obj)def to_dict(obj, func=copy.deepcopy, _visited=None):"""Recursively converts an object into a dictionary representation while avoiding infinite recursion due to circular references.Args:obj: Any Python object to be converted into a dictionary-like structure.func (Callable, optional): A function applied to non-iterable objects. Defaults to `copy.deepcopy`._visited (set, optional): A set of object IDs used to track visited objects and prevent infinite recursion.Returns:dict: A dictionary representation of the input object, with supported collections and dataclassesrecursively processed.Notes:- Supports dataclasses, named tuples, lists, tuples, and dictionaries.- Circular references are detected using object IDs and replaced by `func(obj)`.- Named tuples retain their original type instead of being converted to dictionaries."""# Initialize visited set on first callif _visited is None:_visited = set()# Get object ID to track visited objectsobj_id = id(obj)# If we've seen this object before, return a placeholder to avoid infinite recursionif obj_id in _visited:return func(obj)# For mutable objects, add to visited set before recursingif (isinstance(obj, (dict, list))or is_dataclass(obj)or (isinstance(obj, tuple) and hasattr(obj, "_fields"))):_visited.add(obj_id)if is_dataclass(obj):return {field.name: to_dict(getattr(obj, field.name), func, _visited)for field in fields(obj)}if isinstance(obj, tuple) and hasattr(obj, "_fields"): # named tuplereturn type(obj)(*[to_dict(v, func, _visited) for v in obj])if isinstance(obj, (list, tuple)):return type(obj)([to_dict(v, func, _visited) for v in obj])if isinstance(obj, dict):return type(obj)({to_dict(k, func, _visited): to_dict(v, func, _visited)for k, v in obj.items()})return func(obj)class DataclassMeta(ABCMeta):"""Metaclass for Dataclass.
16 unmodified lines1718192021222316 unmodified linesfrom typing import Any, Dict, List, Optionalfrom .formats import SystemFormatfrom .operators import InstanceFieldOperatorclass SerializeDialog(InstanceFieldOperator):16 unmodified lines1718192021222324252627282930313216 unmodified linesfrom typing import Any, Dict, List, Optionalfrom .formats import SystemFormatfrom .operators import FieldOperator, InstanceFieldOperatorclass ToDialog(FieldOperator):def process_value(self, value: Any) -> Any:dialog = []for question, answer in value:dialog.append({"role": "user", "content": question})dialog.append({"role": "agent", "content": answer})return dialogclass SerializeDialog(InstanceFieldOperator):
2 unmodified lines34567892 unmodified linesfrom .text_utils import to_pretty_stringindx = re.compile(r"^(\d+)$")def is_index(string):2 unmodified lines34567892 unmodified linesfrom .text_utils import to_pretty_stringindx = re.compile(r"^-?\d+$")def is_index(string):
123456721 unmodified lines2930313233343536373839406 unmodified lines4748495051525354555657585960from typing import Optionalfrom .logging_utils import get_loggerlogger = get_logger()21 unmodified lines"""Exception raised for Unitxt errors.Args:message (str):explanation of the erroradditional_info_id (Optional[str]):relative path to additional documentation on webIf set, should be one of the DOCUMENATION_* constants in the error_utils.py file."""def __init__(self, message: str, additional_info_id: Optional[str] = None):6 unmodified lines"""Object to format warning message to log.Args:message (str):explanation of the warningadditional_info_id (Optional[str]):relative path to additional documentation on webIf set, should be one of the DOCUMENATION_* constants in the error_utils.py file."""def __init__(self, message: str, additional_info_id: Optional[str] = None):if additional_info_id is not None:message += additional_info(additional_info_id)logger.warning(message)123456789101121 unmodified lines3334353637383940416 unmodified lines48495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302import refrom contextlib import contextmanagerfrom typing import Any, Optionalfrom .logging_utils import get_loggerfrom .settings_utils import get_constantsconstants = get_constants()logger = get_logger()21 unmodified lines"""Exception raised for Unitxt errors.Args:message (str): explanation of the erroradditional_info_id (Optional[str]): relative path to additional documentation on webIf set, should be one of the DOCUMENTATION_* constants in the error_utils.py file."""def __init__(self, message: str, additional_info_id: Optional[str] = None):6 unmodified lines"""Object to format warning message to log.Args:message (str): explanation of the warningadditional_info_id (Optional[str]): relative path to additional documentation on webIf set, should be one of the DOCUMENTATION_* constants in the error_utils.py file."""def __init__(self, message: str, additional_info_id: Optional[str] = None):if additional_info_id is not None:message += additional_info(additional_info_id)logger.warning(message)context_block_title = "🦄 Unitxt Error Context"def _visible_length(text: str) -> int:import unicodedataansi_escape = re.compile(r"\x1b\[[0-9;]*[a-zA-Z]|\x1b\]8;;[^\x1b]*\x1b\\")clean_text = ansi_escape.sub("", text)width = 0for char in clean_text:if (unicodedata.east_asian_width(char) in ("F", "W")or 0x1F300 <= ord(char) <= 0x1F9FF):width += 2else:width += 1return widthdef _make_object_clickable(full_obj_name: str, display_name: Optional[str] = None) -> str:import osif display_name is None:display_name = full_obj_name.split(".")[-1]if full_obj_name.startswith("unitxt."):parts = full_obj_name.split(".")if len(parts) >= 2:module_path = ".".join(parts[:2])doc_url = f"{Documentation.URL}{module_path}.html#{full_obj_name}"if (os.environ.get("TERM_PROGRAM") in ["iTerm.app", "vscode"]or os.environ.get("TERMINAL_EMULATOR") == "JetBrains-JediTerm"):return f"\033]8;;{doc_url}\033\\{display_name}\033]8;;\033\\"return f"{display_name} ({doc_url})"return display_namedef _get_existing_context(error: Exception):"""Extract existing context from an error if it exists."""if hasattr(error, "__error_context__"):existing = error.__error_context__return (existing["original_message"],existing["context_object"],existing["context"],)return str(error), None, {}def _format_object_context(obj: Any) -> Optional[str]:"""Format an object for display in error context."""if obj is None:return Noneif hasattr(obj, "__class__"):class_name = obj.__class__.__name__module_name = getattr(obj.__class__, "__module__", "")else:obj_type = type(obj)class_name = obj_type.__name__module_name = getattr(obj_type, "__module__", "")if module_name:full_name = f"{module_name}.{class_name}"clickable_object = _make_object_clickable(full_name, class_name)return f"Object: {clickable_object}"return f"Object: {class_name}"def _make_clickable_link(url: str) -> str:"""Create a clickable terminal link."""import osif (os.environ.get("TERM_PROGRAM") in ["iTerm.app", "vscode"]or os.environ.get("TERMINAL_EMULATOR") == "JetBrains-JediTerm"):return f"\033]8;;{url}\033\\link\033]8;;\033\\"return urldef _format_help_context(help_docs) -> list:"""Format help documentation into context parts."""parts = []if isinstance(help_docs, str):parts.append(f"Help: {_make_clickable_link(help_docs)}")elif isinstance(help_docs, dict):for label, url in help_docs.items():parts.append(f"Help ({label}): {_make_clickable_link(url)}")elif isinstance(help_docs, list):for item in help_docs:if isinstance(item, dict) and len(item) == 1:label, url = next(iter(item.items()))parts.append(f"Help ({label}): {_make_clickable_link(url)}")elif isinstance(item, str):parts.append(f"Help: {_make_clickable_link(item)}")return partsdef _build_context_parts(context_object: Any, context: dict) -> list:"""Build the list of context information parts."""parts = []ordered_keys = ["Python","Unitxt","Stage","Stream","Index","Instance","Object","Action",]processed_keys = set()for desired_key in ordered_keys:for actual_key in context.keys():if actual_key.lower() == desired_key.lower():value = ("unknown" if context[actual_key] is None else context[actual_key])parts.append(f"{actual_key.replace('_', ' ').title()}: {value}")processed_keys.add(actual_key)breakif not any(key.lower() == "object" for key in processed_keys):obj_context = _format_object_context(context_object)if obj_context:parts.append(obj_context)processed_keys.add("help")for key, value in context.items():if key not in processed_keys:value = "unknown" if value is None else valueparts.append(f"{key.replace('_', ' ').title()}: {value}")if "help" in context:parts.extend(_format_help_context(context["help"]))else:parts.append(f"Help: {_make_clickable_link(Documentation.URL)}")return partsdef _create_context_box(parts: list) -> str:"""Create a formatted box containing context information."""if not parts:return ""max_width = (max(_visible_length(context_block_title),max(_visible_length(part) for part in parts),)+ 4)top_line = "┌" + "─" * max_width + "┐"bottom_line = "└" + "─" * max_width + "┘"lines = [top_line]lines.append(f"│ {context_block_title}{' ' * (max_width - _visible_length(context_block_title) - 1)}│")lines.append(f"│ {'-' * (max_width - 2)} │")for part in parts:padding = " " * (max_width - _visible_length(part) - 4)lines.append(f"│ - {part}{padding}│")lines.append(bottom_line)return "\n".join(lines)def _store_context_attributes(error: Exception, context_object: Any, context: dict, original_message: str):"""Store context information in error attributes."""error.__error_context__ = {"context_object": context_object,"context": context,"original_message": original_message,}try:error.original_error = type(error)(original_message)except (TypeError, ValueError):error.original_error = Exception(original_message)error.context_object = context_objecterror.context = contextdef _add_context_to_exception(original_error: Exception, context_object: Any = None, **context):"""Add context information to an exception by modifying its message."""original_message, existing_object, existing_context = _get_existing_context(original_error)final_context_object = existing_object or context_objectfinal_context = {"Unitxt": constants.version,"Python": constants.python,**existing_context,**context,}context_parts = _build_context_parts(final_context_object, final_context)context_message = _create_context_box(context_parts)_store_context_attributes(original_error, final_context_object, final_context, original_message)if context_parts:formatted_message = f"\n{context_message}\n\n{original_message}"original_error.args = (formatted_message,)else:original_error.args = (original_message,)@contextmanagerdef error_context(context_object: Any = None, **context):"""Context manager that catches exceptions and re-raises them with additional context.Args:context_object: The object being processed (optional)**context: Any additional context to include in the error message.You can provide any key-value pairs that help identify where the error occurred.Special context keys:- help: Documentation links to help with the error.Can be a string (single URL), dict (label: URL), or list of URLs/dicts.Examples:with error_context(self, operation="validation", item_id=42):result = process_item(item)with error_context(operation="schema_validation", help="https://docs.example.com/schema"):validate_schema(data)with error_context(processor, step="preprocessing", batch_size=32):results = process_batch(batch)"""try:yieldexcept Exception as e:_add_context_to_exception(e, context_object, **context)raise
297 unmodified lines298299300301302303304305306107 unmodified lines41441541641741841924 unmodified lines444445446447448449232 unmodified lines682683684685686687688136 unmodified lines825826827828829297 unmodified linesdataset_query=task_str, **overwrite_args)benchmark = Benchmark(subsets=benchmark_subsets)test_dataset = _source_to_dataset(benchmark, split=args.split)logger.info(f"Dataset loaded successfully. Number of instances: {len(test_dataset)}")107 unmodified lineschat_kwargs_dict=chat_kwargs_dict,)# --- Remote Model (CrossProviderInferenceEngine) ---elif args.model.lower() == "cross_provider":if "model_name" not in model_args_dict:24 unmodified linesmodel=remote_model_name,**model_args_dict,)else:# This case should not be reached due to argparse choiceslogger.error(232 unmodified lines# prepend to the results_path name the time in a wat like this: 2025-04-04T11:37:32timestamp = datetime.now().strftime("%Y-%m-%dT%H:%M:%S")results_path = prepend_timestamp_to_path(results_path, timestamp)samples_path = prepend_timestamp_to_path(samples_path, timestamp)136 unmodified lineslogger.info("Unitxt Evaluation CLI finished successfully.")if __name__ == "__main__":main()297 unmodified lines298299300301302303304305306307308309310107 unmodified lines41841942042142242342442524 unmodified lines450451452453454455456457458232 unmodified lines691692693694695696697136 unmodified lines834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882297 unmodified linesdataset_query=task_str, **overwrite_args)# this hack circumvents an issue with multi-level benchmarks (such Bluebench's translation subset) that fail when wrapped with an additional Benchmark() object.if len(benchmark_subsets) == 1:source = next(iter(benchmark_subsets.values()))else:source = Benchmark(subsets=benchmark_subsets)test_dataset = _source_to_dataset(source, split=args.split)logger.info(f"Dataset loaded successfully. Number of instances: {len(test_dataset)}")107 unmodified lineschat_kwargs_dict=chat_kwargs_dict,)# Keep the actual model name for the resultsargs.model = inference_model.model_name# --- Remote Model (CrossProviderInferenceEngine) ---elif args.model.lower() == "cross_provider":if "model_name" not in model_args_dict:24 unmodified linesmodel=remote_model_name,**model_args_dict,)# Keep the actual model name for the resultsargs.model = inference_model.engine.modelelse:# This case should not be reached due to argparse choiceslogger.error(232 unmodified lines# prepend to the results_path name the time in a wat like this: 2025-04-04T11:37:32timestamp = datetime.now().strftime("%Y-%m-%dT%H-%M-%S")results_path = prepend_timestamp_to_path(results_path, timestamp)samples_path = prepend_timestamp_to_path(samples_path, timestamp)136 unmodified lineslogger.info("Unitxt Evaluation CLI finished successfully.")def extract_scores(directory): # pragma: no coverimport pandas as pddata = []for filename in sorted(os.listdir(directory)):if filename.endswith("evaluation_results.json"):file_path = os.path.join(directory, filename)try:with open(file_path, encoding="utf-8") as f:content = json.load(f)env_info = content.get("environment_info", {})timestamp = env_info.get("timestamp_utc", "N/A")model = env_info.get("parsed_arguments", {}).get("model", "N/A")results = content.get("results", {})row = {}row["Model"] = modelrow["Timestamp"] = timestamprow["Average"] = results.get("score", "N/A")for key in results.keys():if isinstance(results[key], dict):score = results[key].get("score", "N/A")row[key] = scoredata.append(row)except Exception as e:logger.error(f"Error parsing results file {filename}: {e}.")return pd.DataFrame(data).sort_values(by="Timestamp", ascending=True)def summarize_cli():if len(sys.argv) != 2:logger.error("Usage: python summarize_cli_results.py <results-directory>")sys.exit(1)directory = sys.argv[1]df = extract_scores(directory)logger.info(df.to_markdown(index=False))if __name__ == "__main__":main()
12314 unmodified lines181920212223111 unmodified lines13513613713813914029 unmodified lines17017117217317417580 unmodified lines25625725825926026126293 unmodified lines35635735835936036136236355 unmodified lines4194204214224234244254264274284294304 unmodified lines4354364374384394404414424434444454464471 unmodified line4494504514524534544554564575 unmodified lines4634644654664674682 unmodified lines47147247347447547615 unmodified lines49249349449549649711 unmodified lines509510511512513514515516517518519520521import refrom abc import abstractmethodfrom typing import (14 unmodified linesfrom .operator import InstanceOperatorfrom .settings_utils import get_constantsfrom .type_utils import isoftypefrom .utils import retry_connection_with_exponential_backoffconstants = get_constants()111 unmodified linesdef _prepare_instance_fields(self, instance) -> Tuple[str]:instance_fields = {}for field in ("source",constants.instruction_field,29 unmodified linestarget_prefix: str,demos: List[Dict[str, Any]],media: Optional[Dict[str, Any]] = None,) -> str:"""Abstract method for formatting instances in different subclasses.80 unmodified linestarget_prefix: str,demos: List[Dict[str, Any]],media: Optional[Dict[str, Any]] = None,) -> str:demos_string = ""for demo in demos:demo_str = self.demo_format.format(93 unmodified lines)The resulting `messages` is now a dictionary ready for sending to the OpenAI API."""def to_content(self, text: str, media: Dict[str, Any]) -> Union[str, List[Content]]:# Regular expression to find <img> tags with src attributeimg_tag_pattern = re.compile(55 unmodified linestarget_prefix: str,demos: List[Dict[str, Any]],media: Optional[Dict[str, Any]] = None,) -> List[Message]:messages = []if system_prompt or instruction:system_content = self.to_content(system_prompt + ("\n" if system_prompt != "" else "") + instruction,media,)messages.append(4 unmodified lines)for demo_instance in demos:user_content = self.to_content(demo_instance["source"], media)assistant_content = self.to_content(target_prefix + demo_instance["target"], media)messages.extend([{"role": "user", "content": user_content},{"role": "assistant","content": assistant_content,1 unmodified line])last_user_content = self.to_content(source, media)messages.extend([{"role": "user", "content": last_user_content}])return messages5 unmodified linestarget_prefix: str,demos: List[Dict[str, Any]],media: Optional[Dict[str, Any]] = None,) -> Union[str, List[Message]]:chat = self.to_chat(system_prompt,2 unmodified linestarget_prefix,demos,media,)media["images"] = []return chat15 unmodified lines"""model_name: str_requirements_list = ["transformers", "Jinja2"]@retry_connection_with_exponential_backoff(backoff_factor=2)11 unmodified linestarget_prefix: str,demos: List[Dict[str, Any]],media: Optional[Dict[str, Any]] = None,) -> str:chat = self.to_chat(system_prompt, instruction, source, target_prefix, demos, media)return (self.tokenizer.apply_chat_template(chat, tokenize=False, add_generation_prompt=True)+ target_prefix)123414 unmodified lines19202122232425111 unmodified lines13713813914014114214314414529 unmodified lines17517617717817918018180 unmodified lines26226326426526626726826927027193 unmodified lines36536636736836937037137237337437537637737837938038138255 unmodified lines4384394404414424434444454464474484494504514524 unmodified lines4574584594604614624634644654664674684694704714724734744754764774781 unmodified line4804814824834844854864874884894904914924934945 unmodified lines5005015025035045055062 unmodified lines50951051151251351451515 unmodified lines53153253353453553653711 unmodified lines549550551552553554555556557558559560561562563564565import jsonimport refrom abc import abstractmethodfrom typing import (14 unmodified linesfrom .operator import InstanceOperatorfrom .settings_utils import get_constantsfrom .type_utils import isoftypefrom .types import Dialogfrom .utils import retry_connection_with_exponential_backoffconstants = get_constants()111 unmodified linesdef _prepare_instance_fields(self, instance) -> Tuple[str]:instance_fields = {}if "__turns__" in instance:instance_fields["turns"] = instance["__turns__"]for field in ("source",constants.instruction_field,29 unmodified linestarget_prefix: str,demos: List[Dict[str, Any]],media: Optional[Dict[str, Any]] = None,turns: Optional[Dialog] = None,) -> str:"""Abstract method for formatting instances in different subclasses.80 unmodified linestarget_prefix: str,demos: List[Dict[str, Any]],media: Optional[Dict[str, Any]] = None,turns: Optional[Dialog] = None,) -> str:if turns is not None and not source:source = json.dumps(turns)demos_string = ""for demo in demos:demo_str = self.demo_format.format(93 unmodified lines)The resulting `messages` is now a dictionary ready for sending to the OpenAI API.By default, the instruction in the template is placed in a turn with a 'system' role.However, some chat tokenizers, will not place the default system prompt for the model,if there is turn with an explicit 'system' role. To keep the default system prompt,set 'place_instruction_in_user_turns=True'. This will cause the instruction of the templateto be placed in a turn with a 'user' role. Note the instruction will also be placedin every demo turn (if demos are generated.)"""place_instruction_in_user_turns: bool = Falsedef to_content(self, text: str, media: Dict[str, Any]) -> Union[str, List[Content]]:# Regular expression to find <img> tags with src attributeimg_tag_pattern = re.compile(55 unmodified linestarget_prefix: str,demos: List[Dict[str, Any]],media: Optional[Dict[str, Any]] = None,turns: Optional[Dialog] = None,) -> List[Message]:messages = []if system_prompt or (instruction and not self.place_instruction_in_user_turns):system_content = self.to_content(system_prompt+ ("\n" if system_prompt != "" else "")+ (instruction if not self.place_instruction_in_user_turns else ""),media,)messages.append(4 unmodified lines)for demo_instance in demos:if "__turns__" in demo_instance:messages.extend(demo_instance["__turns__"])else:text = demo_instance["source"]if instruction and self.place_instruction_in_user_turns:text = f"{instruction}\n{text}"source_content = self.to_content(text, media)messages.extend([{"role": "user", "content": source_content}])assistant_content = self.to_content(target_prefix + demo_instance["target"],media,)messages.extend([{"role": "assistant","content": assistant_content,1 unmodified line])text = sourceif instruction and self.place_instruction_in_user_turns:text = f"{instruction}\n{text}"if turns is None:last_user_content = self.to_content(text, media)messages.extend([{"role": "user", "content": last_user_content}])else:messages.extend(turns)return messages5 unmodified linestarget_prefix: str,demos: List[Dict[str, Any]],media: Optional[Dict[str, Any]] = None,turns: Optional[Dialog] = None,) -> Union[str, List[Message]]:chat = self.to_chat(system_prompt,2 unmodified linestarget_prefix,demos,media,turns,)media["images"] = []return chat15 unmodified lines"""model_name: strchat_kwargs_dict: Dict[str, str] = {}_requirements_list = ["transformers", "Jinja2"]@retry_connection_with_exponential_backoff(backoff_factor=2)11 unmodified linestarget_prefix: str,demos: List[Dict[str, Any]],media: Optional[Dict[str, Any]] = None,turns: Optional[Dialog] = None,) -> str:chat = self.to_chat(system_prompt, instruction, source, target_prefix, demos, media, turns)return (self.tokenizer.apply_chat_template(chat,tokenize=False,add_generation_prompt=True,**self.chat_kwargs_dict,)+ target_prefix)
1 unmodified line23456784 unmodified lines929394959697986 unmodified lines10510610710810911011111251 unmodified lines1641651661671681691701711721731741751761771781791 unmodified linefrom typing import Dict, Generator, List, Optional, Unionfrom .dataclass import NonPositionalFieldfrom .logging_utils import get_loggerfrom .operator import SourceOperatorfrom .random_utils import new_random_generator84 unmodified linesmax_from_this_split = max_per_this_splitlogger.info(f"Processing {split} from {origin_name}...")try:for instance in multi_stream[split]:if (max_from_this_split is not None6 unmodified linesinstance["subset"].insert(0, origin_name)emitted_from_this_split += 1yield instanceexcept Exception as e:raise RuntimeError(f"Exception in subset: {origin_name}") from eclass WeightedFusion(BaseFusion):51 unmodified linesweights=[self.named_weights[name] for name in population],)[0]iterator = iterators[origin_name]try:instance = next(iterator)if isinstance(origin_name, str):if "subset" not in instance:instance["subset"] = []instance["subset"].insert(0, origin_name)total_examples += 1yield instanceexcept StopIteration:iterators.pop(origin_name)except Exception as e:raise RuntimeError(f"Exception in subset: {origin_name}") from e1 unmodified line234567884 unmodified lines939495969798996 unmodified lines10610710810911011151 unmodified lines1631641651661671681691701711721731741751761771 unmodified linefrom typing import Dict, Generator, List, Optional, Unionfrom .dataclass import NonPositionalFieldfrom .error_utils import error_contextfrom .logging_utils import get_loggerfrom .operator import SourceOperatorfrom .random_utils import new_random_generator84 unmodified linesmax_from_this_split = max_per_this_splitlogger.info(f"Processing {split} from {origin_name}...")with error_context(self, subset=origin_name):for instance in multi_stream[split]:if (max_from_this_split is not None6 unmodified linesinstance["subset"].insert(0, origin_name)emitted_from_this_split += 1yield instanceclass WeightedFusion(BaseFusion):51 unmodified linesweights=[self.named_weights[name] for name in population],)[0]iterator = iterators[origin_name]with error_context(self, subset=origin_name):try:instance = next(iterator)if isinstance(origin_name, str):if "subset" not in instance:instance["subset"] = []instance["subset"].insert(0, origin_name)total_examples += 1yield instanceexcept StopIteration:iterators.pop(origin_name)
38 unmodified lines3940414243444575 unmodified lines12112212312412512610 unmodified lines13713813914014114243 unmodified lines1861871881891901911921931941951961971 unmodified line19920020120220320420537 unmodified lines24324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529642 unmodified lines339340341342343344345175 unmodified lines52152252352452552652752852953053153253364 unmodified lines5985996006016026032 unmodified lines60660760860961061177 unmodified lines68969069169269369469521 unmodified lines71771871972072172272372472572672772872973073134 unmodified lines76676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382422 unmodified lines84784884985085185285363 unmodified lines917918919920921922923924925926927928929930931932933934254 unmodified lines11891190119111921193119457 unmodified lines1252125312541255125612571258125912601261107 unmodified lines136913701371137213731374137513761377137813791380138113821383138413851386138713881389487 unmodified lines187718781879188018811882188310 unmodified lines18941895189618971898189919001901190219033 unmodified lines19071908190919101911191219131914191519161917191819191920192151 unmodified lines1973197419751976197719781979626 unmodified lines260626072608260926102611253 unmodified lines2865286628672868286928706 unmodified lines2877287828792880288128822 unmodified lines2885288628872888288928902891289228932894391 unmodified lines328632873288328932903291144 unmodified lines34363437343834393440344134423443344434453446344734483449345034513452345334543455345638 unmodified linesfrom .base_metric import Metricfrom .dataclass import InternalField, NonPositionalFieldfrom .deprecation_utils import deprecationfrom .error_utils import UnitxtError, UnitxtWarningfrom .image_operators import (EncodeImageToString,ImageDataString,75 unmodified lines| For example: ``[ {.. "top_tokens": [ {"text": "a", 'logprob': }, {"text": "b", 'logprob': } ....]},{.. "top_tokens": [ {"text": "c", 'logprob': }, {"text": "d", 'logprob': } ....]} ]``input_tokens (int) : number of input tokens to the model.output_tokens (int) : number of output tokens to the model.10 unmodified lines"""prediction: Union[str, List[Dict[str, Any]]]input_tokens: Optional[int] = Noneoutput_tokens: Optional[int] = Nonestop_reason: Optional[str] = None43 unmodified linesdef prepare(self):if not settings.mock_inference_mode:super().prepare() # no need to prepare a mockself.prepare_engine()if self.use_cache:from diskcache import Cacheself._cache = Cache(settings.inference_engine_cache_path + self.__class__.__name__)def __call__(1 unmodified linedataset: Union[List[Dict[str, Any]], Dataset],return_meta_data: bool = False,) -> Union[ListWithMetadata[str], ListWithMetadata[TextGenerationInferenceOutput]]:return self.infer(dataset=dataset, return_meta_data=return_meta_data)def get_instance_cache_key(self, instance):instance_key_fields = ["media", "source", "task_data"]37 unmodified linesresult = self._mock_infer(dataset)else:if self.use_cache:number_of_batches = math.ceil(len(dataset) / self.cache_batch_size)result = []for batch_index, batch in enumerate(batched(dataset, self.cache_batch_size)):cached_results = []missing_examples = []for i, item in enumerate(batch):cache_key = self._get_cache_key(item)cached_value = self._cache.get(cache_key)if cached_value is not None:cached_results.append((i, cached_value)) # each element is index in batch, and valueelse:missing_examples.append((i, item)) # each element is index in batch and example# infare on missing examples only, without indiceslogger.info(f"Inferring batch {batch_index + 1} / {number_of_batches} with {len(missing_examples)} instances (found {len(cached_results)} instances in {self._cache.directory})")if len(missing_examples) > 0:inferred_results = self._infer([e[1] for e in missing_examples], return_meta_data)# recombined to index and valueinferred_results = list(zip([e[0] for e in missing_examples], inferred_results))# Add missing examples to cachefor (_, item), (_, prediction) in zip(missing_examples, inferred_results):if prediction is None:continuecache_key = self._get_cache_key(item)self._cache[cache_key] = predictionelse:inferred_results = []# Combine cached and inferred results in original orderbatch_predictions = [p[1] for p in sorted(cached_results + inferred_results)]result.extend(batch_predictions)else:result = self._infer(dataset, return_meta_data)return ListWithMetadata(result,metadata={42 unmodified linesdef to_messages(self, instance):if isinstance(instance["source"], list):return instance["source"]return [{"role": "user",175 unmodified linesdef get_engine_id(self):return get_model_and_label_id(self.model_name, self.label)def decode_tokens(self, tokens: Sequence, inp_length: int) -> List[str]:return self.processor.decode(tokens[inp_length:], skip_special_tokens=True)@staticmethoddef create_string_from_tokens(string_tokens: List[str]) -> str:return "".join(token for token in string_tokens)def make_predictions(self, prepared_inputs: Mapping) -> Mapping:return self.model.generate(**prepared_inputs,64 unmodified linesdef get_return_object(self,output: Union[str, List[Dict[str, Any]]],output_tokens: Optional[int],inp: Optional[str],inp_tokens: Optional[int],2 unmodified linesif return_meta_data:return TextGenerationInferenceOutput(prediction=output,output_tokens=output_tokens if output_tokens is not None else None,input_text=inp,input_tokens=inp_tokens if inp_tokens is not None else None,77 unmodified lines# cause an error because the data is always on the gpu# if torch.cuda.device_count() > 1:# assert self.device == torch.device(0)args["device_map"] = "auto"# else:# if not self.load_in_8bit:# args["device"] = self.device21 unmodified lines**model_args,)def prepare_inputs(self, data: Iterable) -> Mapping:tokenizer_kargs = {}if isinstance(data[0], list):data = self.processor.apply_chat_template(data,tokenize=False,add_generation_prompt=True,**self.chat_kwargs_dict,)tokenizer_kargs["add_special_tokens"] = Falseif self.processor.pad_token is None:34 unmodified linestotal=len(dataset) // self.batch_size,):# Get the current batchbatch_sources = [instance["source"] for instance in batch]# --- Process the current batch ---# 1. Tokenize inputs for the batchtokenized_inputs = self.prepare_inputs(batch_sources)# 2. Determine input length (handle encoder-decoder models)input_length = (1if self.model.config.is_encoder_decoderelse tokenized_inputs.input_ids.shape[1])# 3. Make predictions for the batchpredictions = self.make_predictions(tokenized_inputs)sequences = predictions.sequences # Sequences for the current batch# 4. Decode tokens for the batchstring_tokens_batch = [self.decode_tokens(sequence, input_length) for sequence in sequences]# 5. Calculate logprobs or create strings for the batchfinal_outputs_batch = (self.get_logprobs(predictions, string_tokens_batch)if return_logprobselse [self.create_string_from_tokens(strings)for strings in string_tokens_batch])# 6. Create return objects for the batchbatch_results = [self.get_return_object(output=final_outputs_batch[j], # Output for the j-th item in the batchoutput_tokens=len(string_tokens_batch[j]),inp=batch[j]["source"], # Original input for the j-th iteminp_tokens=len(tokenized_inputs.encodings[j].tokens)if tokenized_inputs.encodings is not Noneelse None,return_meta_data=return_meta_data,)for j in range(len(sequences)) # Iterate through items in the current batch]# Add results from this batch to the overall listall_final_outputs.extend(batch_results)# --- End of batch processing ---return all_final_outputs22 unmodified linesself, sequences: Sequence, scores: Sequence, beam_indices: Optional[int]) -> Sequence:if not hasattr(self.model.config, "vocab_size"):self.model.config.vocab_size = self.model.vocab_sizereturn super().compute_transition_scores(sequences, scores, beam_indices)63 unmodified linespredictions = self.make_predictions(processed_inputs)string_tokens = self.decode_tokens(predictions.sequences[0], input_len)final_outputs = (self.get_logprobs(predictions, [string_tokens])[0]if return_logprobselse self.create_string_from_tokens(string_tokens))results.append(self.get_return_object(output=final_outputs,output_tokens=len(string_tokens),inp=instance["source"],inp_tokens=None,return_meta_data=return_meta_data,254 unmodified linesif return_meta_data:return TextGenerationInferenceOutput(prediction=output["generated_text"],model_name=self.model_name,inference_type=self.label,input_text=inp,57 unmodified linesfor instance in dataset]def get_return_object(self, predict_result, instance, return_meta_data):if return_meta_data:return TextGenerationInferenceOutput(prediction=predict_result,input_tokens=len(instance["source"]),output_tokens=len(predict_result),model_name=self.model_name,107 unmodified linesreturn get_model_and_label_id(self.model, self.label)def prepare_engine(self):passdef _infer(self,dataset: Union[List[Dict[str, Any]], Dataset],return_meta_data: bool = False,) -> Union[List[str], List[TextGenerationInferenceOutput]]:import ollamaargs = self.to_dict([StandardAPIParamsMixin])results = []model = args.pop("model")for instance in dataset:messages = self.to_messages(instance)response = ollama.chat(messages=messages,model=model,options=args,487 unmodified linesf"Error predicting instance {messages}:{e}. Returning empty prediction")return TextGenerationInferenceOutput(prediction="-", input_tokens=0, output_tokens=0)@run_with_imap10 unmodified linestop_logprobs_response = response.choices[0].logprobs.contentpred_output = [{"top_tokens": [{"text": obj.token, "logprob": obj.logprob}for obj in generated_token.top_logprobs]}for generated_token in top_logprobs_response]3 unmodified lineslogging.error(f"Error predicting instance {messages}:{e}. Returning empty prediction")prediction = [{"top_tokens": [{"text": "-", "logprob": 0}]}]return TextGenerationInferenceOutput(prediction=prediction, input_tokens=0, output_tokens=0)def get_return_object(self, predict_result, response, return_meta_data):if return_meta_data:return TextGenerationInferenceOutput(prediction=predict_result,input_tokens=response.usage.prompt_tokens,output_tokens=response.usage.completion_tokens,model_name=self.model_name,51 unmodified lineslabel: str = "rits"data_classification_policy = ["public", "proprietary"]model_names_dict = {"microsoft/phi-4": "microsoft-phi-4"}def get_default_headers(self):return {"RITS_API_KEY": self.credentials["api_key"]}626 unmodified linesif return_meta_data:return TextGenerationInferenceOutput(prediction=predict_result,input_tokens=result["input_token_count"],output_tokens=result["generated_token_count"],model_name=self.model_name or self.deployment_id,253 unmodified linestool_call = data[idx]["tools"]["tools"] is not Noneoutput = response["choices"][0][output_type]if tool_call:if "tool_calls" in output:func = output["tool_calls"][0]["function"]6 unmodified linesresults.append(self.get_return_object(prediction,response,str(inp),return_meta_data,2 unmodified linesreturn resultsdef get_return_object(self, predict_result, result, input_text, return_meta_data):if return_meta_data:return TextGenerationInferenceOutput(prediction=predict_result,input_tokens=result["usage"]["prompt_tokens"],output_tokens=len(predict_result)if isinstance(predict_result, list)391 unmodified linesprediction = response["choices"][0]["message"]["content"] or ""return TextGenerationInferenceOutput(prediction=prediction,input_tokens=usage.get("prompt_tokens"),output_tokens=usage.get("completion_tokens"),model_name=response.get("model", self.model),144 unmodified lines},"rits": {"granite-3-8b-instruct": "ibm-granite/granite-3.0-8b-instruct","granite-3-2-8b-instruct": "ibm-granite/granite-3.2-8b-instruct","granite-3-3-8b-instruct": "ibm-granite/granite-3.3-8b-instruct","llama-3-1-8b-instruct": "meta-llama/llama-3-1-8b-instruct","llama-3-1-70b-instruct": "meta-llama/llama-3-1-70b-instruct","llama-3-1-405b-instruct": "meta-llama/llama-3-1-405b-instruct-fp8","llama-3-1-405b-instruct-fp8": "meta-llama/llama-3-1-405b-instruct-fp8","llama-3-2-11b-vision-instruct": "meta-llama/Llama-3.2-11B-Vision-Instruct","llama-3-2-90b-vision-instruct": "meta-llama/Llama-3.2-90B-Vision-Instruct","llama-3-3-70b-instruct": "meta-llama/llama-3-3-70b-instruct","llama-4-scout": "llama-4-scout-17b-16e","llama-4-maverick": "llama-4-mvk-17b-128e-fp8","mistral-large-instruct": "mistralai/mistral-large-instruct-2407","mixtral-8x7b-instruct": "mistralai/mixtral-8x7B-instruct-v0.1","mixtral-8x7b-instruct-v01": "mistralai/mixtral-8x7B-instruct-v0.1","deepseek-v3": "deepseek-ai/deepseek-v3-h200","granite-guardian-3-2-3b-a800m": "ibm-granite/granite-guardian-3.2-3b-a800m","granite-guardian-3-2-5b": "ibm-granite/granite-guardian-3.2-5b",},38 unmodified lines3940414243444575 unmodified lines12112212312412512612712810 unmodified lines13914014114214314414543 unmodified lines1891901911921931941951961971981992002012022032042052062071 unmodified line20921021121221321421521621721821922037 unmodified lines25825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532642 unmodified lines369370371372373374375376377378379380381382383384175 unmodified lines56056156256356456564 unmodified lines6306316326336346356362 unmodified lines63964064164264364464577 unmodified lines72372472572672772872973021 unmodified lines75275375475575675775875976076176276376476576676776876977077177234 unmodified lines80780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687722 unmodified lines90090190290390490590690790890963 unmodified lines97397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007254 unmodified lines126212631264126512661267126857 unmodified lines1326132713281329133013311332133313341335133613371338107 unmodified lines1446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470487 unmodified lines195819591960196119621963196410 unmodified lines1975197619771978197919801981198219831984198519863 unmodified lines19901991199219931994199519961997199819992000200120022003200420052006200720082009201051 unmodified lines206220632064206520662067206820692070207120722073626 unmodified lines2700270127022703270427052706253 unmodified lines296029612962296329642965296629676 unmodified lines29742975297629772978297929802 unmodified lines2983298429852986298729882989299029912992299329942995391 unmodified lines3387338833893390339133923393144 unmodified lines353835393540354135423543354435453546354735483549355035513552355335543555355635573558355938 unmodified linesfrom .base_metric import Metricfrom .dataclass import InternalField, NonPositionalFieldfrom .deprecation_utils import deprecationfrom .error_utils import UnitxtError, UnitxtWarning, error_contextfrom .image_operators import (EncodeImageToString,ImageDataString,75 unmodified lines| For example: ``[ {.. "top_tokens": [ {"text": "a", 'logprob': }, {"text": "b", 'logprob': } ....]},{.. "top_tokens": [ {"text": "c", 'logprob': }, {"text": "d", 'logprob': } ....]} ]``generated_text (str): The generated text generated by the model (in both _infer and _infer_log_probs calls).input_tokens (int) : number of input tokens to the model.output_tokens (int) : number of output tokens to the model.10 unmodified lines"""prediction: Union[str, List[Dict[str, Any]]]generated_text: strinput_tokens: Optional[int] = Noneoutput_tokens: Optional[int] = Nonestop_reason: Optional[str] = None43 unmodified linesdef prepare(self):if not settings.mock_inference_mode:super().prepare() # no need to prepare a mockwith error_context(self,stage="Prepare Inference Engine",help="https://www.unitxt.ai/en/latest/docs/inference.html",):self.prepare_engine()if self.use_cache:from diskcache import Cacheself._cache = Cache(os.path.join(settings.inference_engine_cache_path, self.__class__.__name__))def __call__(1 unmodified linedataset: Union[List[Dict[str, Any]], Dataset],return_meta_data: bool = False,) -> Union[ListWithMetadata[str], ListWithMetadata[TextGenerationInferenceOutput]]:with error_context(self,stage="Running Inference",help="https://www.unitxt.ai/en/latest/docs/inference.html",):return self.infer(dataset=dataset, return_meta_data=return_meta_data)def get_instance_cache_key(self, instance):instance_key_fields = ["media", "source", "task_data"]37 unmodified linesresult = self._mock_infer(dataset)else:if self.use_cache:with error_context(self,stage="Inference Cache Handling",help="https://www.unitxt.ai/en/latest/docs/inference.html",):number_of_batches = math.ceil(len(dataset) / self.cache_batch_size)result = []for batch_index, batch in enumerate(batched(dataset, self.cache_batch_size)):cached_results = []missing_examples = []for i, item in enumerate(batch):cache_key = self._get_cache_key(item)cached_value = self._cache.get(cache_key)if cached_value is not None:cached_results.append((i, cached_value)) # each element is index in batch, and valueelse:missing_examples.append((i, item)) # each element is index in batch and example# infare on missing examples only, without indiceslogger.info(f"Inferring batch {batch_index + 1} / {number_of_batches} with {len(missing_examples)} instances (found {len(cached_results)} instances in {self._cache.directory})")if len(missing_examples) > 0:with error_context(self,stage="Running Inference",help="https://www.unitxt.ai/en/latest/docs/inference.html",):inferred_results = self._infer([e[1] for e in missing_examples], return_meta_data)# recombined to index and valueinferred_results = list(zip([e[0] for e in missing_examples], inferred_results))# Add missing examples to cachefor (_, item), (_, prediction) in zip(missing_examples, inferred_results):if prediction is None:continuecache_key = self._get_cache_key(item)self._cache[cache_key] = predictionelse:inferred_results = []# Combine cached and inferred results in original orderbatch_predictions = [p[1] for p in sorted(cached_results + inferred_results)]result.extend(batch_predictions)else:with error_context(self,stage="Running Inference",help="https://www.unitxt.ai/en/latest/docs/inference.html",):result = self._infer(dataset, return_meta_data)return ListWithMetadata(result,metadata={42 unmodified linesdef to_messages(self, instance):if isinstance(instance["source"], list):messages = []for message in instance["source"]:if "tool_calls" in message:for tool_call in message["tool_calls"]:if not isinstance(tool_call["function"]["arguments"], str):tool_call["function"]["arguments"] = json.dumps(tool_call["function"]["arguments"])messages.append(message)return messagesreturn [{"role": "user",175 unmodified linesdef get_engine_id(self):return get_model_and_label_id(self.model_name, self.label)def make_predictions(self, prepared_inputs: Mapping) -> Mapping:return self.model.generate(**prepared_inputs,64 unmodified linesdef get_return_object(self,output: Union[str, List[Dict[str, Any]]],generated_text: str,output_tokens: Optional[int],inp: Optional[str],inp_tokens: Optional[int],2 unmodified linesif return_meta_data:return TextGenerationInferenceOutput(prediction=output,generated_text=generated_text,output_tokens=output_tokens if output_tokens is not None else None,input_text=inp,input_tokens=inp_tokens if inp_tokens is not None else None,77 unmodified lines# cause an error because the data is always on the gpu# if torch.cuda.device_count() > 1:# assert self.device == torch.device(0)if self.device_map is None:args["device_map"] = "auto"# else:# if not self.load_in_8bit:# args["device"] = self.device21 unmodified lines**model_args,)def prepare_inputs(self, data: Iterable, tools: Iterable) -> Mapping:tokenizer_kargs = {}if isinstance(data[0], list):processed = []for item, item_tools in zip(data, tools):processed.append(self.processor.apply_chat_template(item,tokenize=False,tools=item_tools,add_generation_prompt=True,**self.chat_kwargs_dict,))data = processedtokenizer_kargs["add_special_tokens"] = Falseif self.processor.pad_token is None:34 unmodified linestotal=len(dataset) // self.batch_size,):# Get the current batchsources = []tools = []for instance in batch:sources.append(instance["source"])if "task_data" in instance and "__tools__" in instance["task_data"]:task_data = instance["task_data"]if isinstance(task_data, str):task_data = json.loads(task_data)tools.append(task_data["__tools__"])else:tools.append(None)# Tokenize inputs for the batchtokenized_inputs = self.prepare_inputs(sources, tools)# Determine input length (handle encoder-decoder models)input_length = (1if self.model.config.is_encoder_decoderelse tokenized_inputs.input_ids.shape[1])# Make predictions for the batchpredictions = self.make_predictions(tokenized_inputs)sequences = predictions.sequences # Sequences for the current batchoutput_tokens = sequences[:, input_length:]output_tokens_strings = []for tokens in output_tokens:output_tokens_strings.append([self.processor.decode(token, skip_special_tokens=True)for token in tokens])output_strings = []for tokens in output_tokens:output_strings.append(self.processor.decode(tokens, skip_special_tokens=True))if return_logprobs:outputs = self.get_logprobs(predictions, output_tokens_strings)else:outputs = output_strings# Create return objects for the batchbatch_results = []for i in range(len(sequences)):batch_results.append(self.get_return_object(output=outputs[i],generated_text=output_strings[i],output_tokens=len(output_tokens_strings[i]),inp=sources[i],inp_tokens=len(tokenized_inputs.encodings[i].tokens)if tokenized_inputs.encodings is not Noneelse None,return_meta_data=return_meta_data,))all_final_outputs.extend(batch_results)return all_final_outputs22 unmodified linesself, sequences: Sequence, scores: Sequence, beam_indices: Optional[int]) -> Sequence:if not hasattr(self.model.config, "vocab_size"):try:self.model.config.vocab_size = self.model.vocab_sizeexcept:self.model.config.vocab_size = self.model.config.text_config.vocab_sizereturn super().compute_transition_scores(sequences, scores, beam_indices)63 unmodified linespredictions = self.make_predictions(processed_inputs)sequences = predictions.sequences # Sequences for the current batchoutput_tokens = sequences[:, input_len:]output_tokens_strings = []for tokens in output_tokens:output_tokens_strings.append([self.processor.decode(token, skip_special_tokens=True)for token in tokens])output_strings = []for tokens in output_tokens:output_strings.append(self.processor.decode(tokens, skip_special_tokens=True))if return_logprobs:final_outputs = self.get_logprobs(predictions, output_tokens_strings)else:final_outputs = output_stringsresults.append(self.get_return_object(output=final_outputs[0],generated_text=output_strings,output_tokens=len(output_tokens_strings[0]),inp=instance["source"],inp_tokens=None,return_meta_data=return_meta_data,254 unmodified linesif return_meta_data:return TextGenerationInferenceOutput(prediction=output["generated_text"],generated_text=output["generated_text"],model_name=self.model_name,inference_type=self.label,input_text=inp,57 unmodified linesfor instance in dataset]def get_return_object(self, predict_result, generated_text, instance, return_meta_data):if return_meta_data:return TextGenerationInferenceOutput(prediction=predict_result,generated_text=self.default_inference_value,input_tokens=len(instance["source"]),output_tokens=len(predict_result),model_name=self.model_name,107 unmodified linesreturn get_model_and_label_id(self.model, self.label)def prepare_engine(self):from ollama import Clientself.client = Client(host=self.credentials["api_base"]if self.credentials is not None and "api_base" in self.credentialselse None)def _infer(self,dataset: Union[List[Dict[str, Any]], Dataset],return_meta_data: bool = False,) -> Union[List[str], List[TextGenerationInferenceOutput]]:args = self.to_dict([StandardAPIParamsMixin])results = []model = args.pop("model")for instance in dataset:messages = self.to_messages(instance)response = self.client.chat(messages=messages,model=model,options=args,487 unmodified linesf"Error predicting instance {messages}:{e}. Returning empty prediction")return TextGenerationInferenceOutput(prediction="-", generated_text="-", input_tokens=0, output_tokens=0)@run_with_imap10 unmodified linestop_logprobs_response = response.choices[0].logprobs.contentpred_output = [{"text": generated_token.token,"logprob": generated_token.logprob,"top_tokens": [{"text": obj.token, "logprob": obj.logprob}for obj in generated_token.top_logprobs],}for generated_token in top_logprobs_response]3 unmodified lineslogging.error(f"Error predicting instance {messages}:{e}. Returning empty prediction")prediction = [{"text": "-", "logprob": 0, "top_tokens": [{"text": "-", "logprob": 0}]}]return TextGenerationInferenceOutput(prediction=prediction,generated_text=prediction,input_tokens=0,output_tokens=0,)def get_return_object(self, predict_result, response, return_meta_data):if return_meta_data:return TextGenerationInferenceOutput(prediction=predict_result,generated_text=response.choices[0].message.content,input_tokens=response.usage.prompt_tokens,output_tokens=response.usage.completion_tokens,model_name=self.model_name,51 unmodified lineslabel: str = "rits"data_classification_policy = ["public", "proprietary"]model_names_dict = {"microsoft/phi-4": "microsoft-phi-4","meta-llama/llama-4-maverick-17b-128e-instruct-fp8": "llama-4-mvk-17b-128e-fp8","deepseek-ai/DeepSeek-V3": "deepseek-v3-h200","meta-llama/Llama-3.1-8B-Instruct": "llama-3-1-8b-instruct",}def get_default_headers(self):return {"RITS_API_KEY": self.credentials["api_key"]}626 unmodified linesif return_meta_data:return TextGenerationInferenceOutput(prediction=predict_result,generated_text=result["generated_text"],input_tokens=result["input_token_count"],output_tokens=result["generated_token_count"],model_name=self.model_name or self.deployment_id,253 unmodified linestool_call = data[idx]["tools"]["tools"] is not Noneoutput = response["choices"][0][output_type]if "content" not in output:output["content"] = ""if tool_call:if "tool_calls" in output:func = output["tool_calls"][0]["function"]6 unmodified linesresults.append(self.get_return_object(prediction,response["choices"][0]["message"]["content"],response,str(inp),return_meta_data,2 unmodified linesreturn resultsdef get_return_object(self, predict_result, generated_text, result, input_text, return_meta_data):if return_meta_data:return TextGenerationInferenceOutput(prediction=predict_result,generated_text=generated_text,input_tokens=result["usage"]["prompt_tokens"],output_tokens=len(predict_result)if isinstance(predict_result, list)391 unmodified linesprediction = response["choices"][0]["message"]["content"] or ""return TextGenerationInferenceOutput(prediction=prediction,generated_text=response["choices"][0]["message"]["content"],input_tokens=usage.get("prompt_tokens"),output_tokens=usage.get("completion_tokens"),model_name=response.get("model", self.model),144 unmodified lines},"rits": {"granite-3-8b-instruct": "ibm-granite/granite-3.0-8b-instruct","granite-3-1-8b-instruct": "ibm-granite/granite-3.1-8b-instruct","granite-3-2-8b-instruct": "ibm-granite/granite-3.2-8b-instruct","granite-3-3-8b-instruct": "ibm-granite/granite-3.3-8b-instruct","llama-3-1-8b-instruct": "meta-llama/Llama-3.1-8B-Instruct","llama-3-1-70b-instruct": "meta-llama/llama-3-1-70b-instruct","llama-3-1-405b-instruct": "meta-llama/llama-3-1-405b-instruct-fp8","llama-3-1-405b-instruct-fp8": "meta-llama/llama-3-1-405b-instruct-fp8","llama-3-2-11b-vision-instruct": "meta-llama/Llama-3.2-11B-Vision-Instruct","llama-3-2-90b-vision-instruct": "meta-llama/Llama-3.2-90B-Vision-Instruct","llama-3-3-70b-instruct": "meta-llama/llama-3-3-70b-instruct","llama-4-scout": "meta-llama/llama-4-scout-17b-16e","llama-4-maverick": "meta-llama/llama-4-maverick-17b-128e-instruct-fp8","mistral-large-instruct": "mistralai/mistral-large-instruct-2407","mixtral-8x7b-instruct": "mistralai/mixtral-8x7B-instruct-v0.1","mixtral-8x7b-instruct-v01": "mistralai/mixtral-8x7B-instruct-v0.1","deepseek-v3": "deepseek-ai/DeepSeek-V3","granite-guardian-3-2-3b-a800m": "ibm-granite/granite-guardian-3.2-3b-a800m","granite-guardian-3-2-5b": "ibm-granite/granite-guardian-3.2-5b",},
124 unmodified lines12512612712812913013166 unmodified lines198199200201202203204124 unmodified linesEvaluatorNameEnum.GRANITE3_1_8B: "granite-3-1-8b-instruct",EvaluatorNameEnum.GRANITE3_2_8B: "granite-3-2-8b-instruct",EvaluatorNameEnum.GRANITE3_3_8B: "granite-3-3-8b-instruct",EvaluatorNameEnum.DEEPSEEK_V3: "deepseek-ai/DeepSeek-V3",EvaluatorNameEnum.GEMMA_2_5_PRO: "gemma-2-5-pro",EvaluatorNameEnum.GEMINI_2_5_FLASH: "gemini-2-5-flash",}66 unmodified lines[ModelProviderEnum.WATSONX,ModelProviderEnum.TOGETHER_AI,ModelProviderEnum.RITS,ModelProviderEnum.OLLAMA,],),124 unmodified lines12512612712812913013166 unmodified lines198199200201202203124 unmodified linesEvaluatorNameEnum.GRANITE3_1_8B: "granite-3-1-8b-instruct",EvaluatorNameEnum.GRANITE3_2_8B: "granite-3-2-8b-instruct",EvaluatorNameEnum.GRANITE3_3_8B: "granite-3-3-8b-instruct",EvaluatorNameEnum.DEEPSEEK_V3: "deepseek-v3",EvaluatorNameEnum.GEMMA_2_5_PRO: "gemma-2-5-pro",EvaluatorNameEnum.GEMINI_2_5_FLASH: "gemini-2-5-flash",}66 unmodified lines[ModelProviderEnum.WATSONX,ModelProviderEnum.TOGETHER_AI,ModelProviderEnum.OLLAMA,],),
65 unmodified lines6667686970717217 unmodified lines90919293949596979899100101102103104105106107108109110111112105 unmodified lines218219220221222223224225226227228229230283 unmodified lines51451551651751851952052152237 unmodified lines56056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059139 unmodified lines631632633634635636637638212 unmodified lines85185285385485585685785885986086186286386486586686786877 unmodified lines946947948949950951952953954955956957958959960961962963964965966967159 unmodified lines112711281129113011311132113365 unmodified linesfrom .dataclass import NonPositionalFieldfrom .dict_utils import dict_getfrom .error_utils import Documentation, UnitxtError, UnitxtWarningfrom .fusion import FixedFusionfrom .logging_utils import get_loggerfrom .operator import SourceOperator17 unmodified lines@retry_connection_with_exponential_backoff(backoff_factor=2)def hf_load_dataset(path: str, *args, **kwargs):if settings.hf_offline_datasets_path is not None:path = os.path.join(settings.hf_offline_datasets_path, path)try:return _hf_load_dataset(path,*args,**kwargs,verification_mode="no_checks",trust_remote_code=settings.allow_unverified_code,download_mode="force_redownload"if settings.disable_hf_datasets_cacheelse "reuse_dataset_if_exists",)except ValueError as e:if "trust_remote_code" in str(e):raise UnitxtUnverifiedCodeError(path) from eraise e # Re raise@retry_connection_with_exponential_backoff(backoff_factor=2)105 unmodified linespassdef load_data(self) -> MultiStream:try:iterables = self.load_iterables()except Exception as e:raise UnitxtError(f"Error in loader:\n{self}") from eif isoftype(iterables, MultiStream):return iterablesreturn MultiStream.from_iterables(iterables, copying=True)def process(self) -> MultiStream:self._maybe_set_classification_policy()283 unmodified linessep: str = ","def read_dataframe(self, file) -> pd.DataFrame:return pd.read_csv(file, sep=self.sep, low_memory=self.streaming, **self.get_args())def read_file(source) -> bytes:37 unmodified linesdata_field: Optional[str] = Nonedef read_dataframe(self, file) -> pd.DataFrame:args = self.get_args()if not self.lines:data = json.loads(read_file(file))if self.data_field:instances = dict_get(data, self.data_field)if not isoftype(instances, List[Dict[str, Any]]):raise UnitxtError(f"{self.data_field} of file {file} is not a list of dictionariess in LoadJsonFile loader")else:if isoftype(data, Dict[str, Any]):instances = [data]elif isoftype(data, List[Dict[str, Any]]):instances = dataelse:raise UnitxtError(f"data of file {file} is not dictionary or a list of dictionaries in LoadJsonFile loader")dataframe = pd.DataFrame(instances)else:if self.data_field is not None:raise UnitxtError("Can not load from a specific 'data_field' when loading multiple lines (lines=True)")dataframe = pd.read_json(file, lines=self.lines, **args)return dataframeclass LoadFromSklearn(LazyLoader):39 unmodified linesdataset_id = str(self) + "_" + splitdataset = self.__class__._loader_cache.get(dataset_id, None)if dataset is None:split_data = self.downloader(subset=split)targets = [split_data["target_names"][t] for t in split_data["target"]]df = pd.DataFrame([split_data["data"], targets]).Tdf.columns = ["data", "target"]dataset = df.to_dict("records")212 unmodified linesif self.data_dir is not Noneelse data_file)with tempfile.NamedTemporaryFile() as temp_file:# Download to a temporary file in same file partition, and then do an atomic moveself._download_from_cos(cos,self.bucket_name,object_key,local_dir + "/" + os.path.basename(temp_file.name),)os.renames(local_dir + "/" + os.path.basename(temp_file.name),local_dir + "/" + data_file,)if isinstance(self.data_files, list):dataset = hf_load_dataset(local_dir, streaming=False, field=self.data_field)77 unmodified linesdef verify(self):super().verify()if not isoftype(self.data, Dict[str, List[Dict[str, Any]]]):raise ValueError(f"Passed data to LoadFromDictionary is not of type Dict[str, List[Dict[str, Any]]].\n"f"Expected data should map between split name and list of instances.\n"f"Received value: {self.data}\n")for split in self.data.keys():if len(self.data[split]) == 0:raise ValueError(f"Split {split} has no instances.")first_instance = self.data[split][0]for instance in self.data[split]:if instance.keys() != first_instance.keys():raise ValueError(f"Not all instances in split '{split}' have the same fields.\n"f"instance {instance} has different fields different from {first_instance}")def _maybe_set_classification_policy(self):self.set_default_data_classification(159 unmodified lineschunksize: int = 100000loader_limit: Optional[int] = Nonestreaming: bool = Falseapi_key_env_var: Optional[str] = ""headers: Optional[Dict[str, Any]] = Nonedata_field: str = "data"method: str = "GET"65 unmodified lines6667686970717217 unmodified lines90919293949596979899100101102103104105106107108109110111112113114115116105 unmodified lines222223224225226227228229230231232233234235236283 unmodified lines52052152252352452552652752852953053153237 unmodified lines57057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460539 unmodified lines645646647648649650651652653654655656212 unmodified lines86987087187287387487587687787887988088188288388488588688788888989077 unmodified lines968969970971972973974975976977978979980981982983984985986987988989990991992993159 unmodified lines115311541155115611571158115965 unmodified linesfrom .dataclass import NonPositionalFieldfrom .dict_utils import dict_getfrom .error_utils import Documentation, UnitxtError, UnitxtWarning, error_contextfrom .fusion import FixedFusionfrom .logging_utils import get_loggerfrom .operator import SourceOperator17 unmodified lines@retry_connection_with_exponential_backoff(backoff_factor=2)def hf_load_dataset(path: str, *args, **kwargs):with error_context(stage="Raw Dataset Download",help="https://www.unitxt.ai/en/latest/unitxt.loaders.html#module-unitxt.loaders",):if settings.hf_offline_datasets_path is not None:path = os.path.join(settings.hf_offline_datasets_path, path)try:return _hf_load_dataset(path,*args,**kwargs,verification_mode="no_checks",trust_remote_code=settings.allow_unverified_code,download_mode="force_redownload"if settings.disable_hf_datasets_cacheelse "reuse_dataset_if_exists",)except ValueError as e:if "trust_remote_code" in str(e):raise UnitxtUnverifiedCodeError(path) from eraise e # Re raise@retry_connection_with_exponential_backoff(backoff_factor=2)105 unmodified linespassdef load_data(self) -> MultiStream:with error_context(self,stage="Data Loading",help="https://www.unitxt.ai/en/latest/unitxt.loaders.html#module-unitxt.loaders",):iterables = self.load_iterables()if isoftype(iterables, MultiStream):return iterablesreturn MultiStream.from_iterables(iterables, copying=True)def process(self) -> MultiStream:self._maybe_set_classification_policy()283 unmodified linessep: str = ","def read_dataframe(self, file) -> pd.DataFrame:with error_context(stage="Raw Dataset Loading",help="https://www.unitxt.ai/en/latest/unitxt.loaders.html#module-unitxt.loaders",):return pd.read_csv(file, sep=self.sep, low_memory=self.streaming, **self.get_args())def read_file(source) -> bytes:37 unmodified linesdata_field: Optional[str] = Nonedef read_dataframe(self, file) -> pd.DataFrame:with error_context(stage="Raw Dataset Loading",help="https://www.unitxt.ai/en/latest/unitxt.loaders.html#module-unitxt.loaders",):args = self.get_args()if not self.lines:data = json.loads(read_file(file))if self.data_field:instances = dict_get(data, self.data_field)if not isoftype(instances, List[Dict[str, Any]]):raise UnitxtError(f"{self.data_field} of file {file} is not a list of dictionariess in LoadJsonFile loader")else:if isoftype(data, Dict[str, Any]):instances = [data]elif isoftype(data, List[Dict[str, Any]]):instances = dataelse:raise UnitxtError(f"data of file {file} is not dictionary or a list of dictionaries in LoadJsonFile loader")dataframe = pd.DataFrame(instances)else:if self.data_field is not None:raise UnitxtError("Can not load from a specific 'data_field' when loading multiple lines (lines=True)")dataframe = pd.read_json(file, lines=self.lines, **args)return dataframeclass LoadFromSklearn(LazyLoader):39 unmodified linesdataset_id = str(self) + "_" + splitdataset = self.__class__._loader_cache.get(dataset_id, None)if dataset is None:with error_context(stage="Raw Dataset Loading",help="https://www.unitxt.ai/en/latest/unitxt.loaders.html#module-unitxt.loaders",):split_data = self.downloader(subset=split)targets = [split_data["target_names"][t] for t in split_data["target"]]df = pd.DataFrame([split_data["data"], targets]).Tdf.columns = ["data", "target"]dataset = df.to_dict("records")212 unmodified linesif self.data_dir is not Noneelse data_file)with error_context(stage="Raw Dataset Download",help="https://www.unitxt.ai/en/latest/unitxt.loaders.html#module-unitxt.loaders",):with tempfile.NamedTemporaryFile() as temp_file:# Download to a temporary file in same file partition, and then do an atomic moveself._download_from_cos(cos,self.bucket_name,object_key,local_dir + "/" + os.path.basename(temp_file.name),)os.renames(local_dir + "/" + os.path.basename(temp_file.name),local_dir + "/" + data_file,)if isinstance(self.data_files, list):dataset = hf_load_dataset(local_dir, streaming=False, field=self.data_field)77 unmodified linesdef verify(self):super().verify()with error_context(stage="Dataset Loading",help="https://www.unitxt.ai/en/latest/unitxt.loaders.html#module-unitxt.loaders",):if not isoftype(self.data, Dict[str, List[Dict[str, Any]]]):raise ValueError(f"Passed data to LoadFromDictionary is not of type Dict[str, List[Dict[str, Any]]].\n"f"Expected data should map between split name and list of instances.\n"f"Received value: {self.data}\n")for split in self.data.keys():if len(self.data[split]) == 0:raise ValueError(f"Split {split} has no instances.")first_instance = self.data[split][0]for instance in self.data[split]:if instance.keys() != first_instance.keys():raise ValueError(f"Not all instances in split '{split}' have the same fields.\n"f"instance {instance} has different fields different from {first_instance}")def _maybe_set_classification_policy(self):self.set_default_data_classification(159 unmodified lineschunksize: int = 100000loader_limit: Optional[int] = Nonestreaming: bool = Falseapi_key_env_var: Optional[str] = Noneheaders: Optional[Dict[str, Any]] = Nonedata_field: str = "data"method: str = "GET"
55 unmodified lines565758596061622 unmodified lines65666768697055 unmodified linesfrom .span_lableing_operators import __file__ as _from .split_utils import __file__ as _from .splitters import __file__ as _from .sql_utils import __file__ as _from .standard import __file__ as _from .stream import __file__ as _from .stream_operators import __file__ as _2 unmodified linesfrom .system_prompts import __file__ as _from .task import __file__ as _from .templates import __file__ as _from .text_utils import __file__ as _from .type_utils import __file__ as _from .types import __file__ as _55 unmodified lines5657585960612 unmodified lines6465666768697055 unmodified linesfrom .span_lableing_operators import __file__ as _from .split_utils import __file__ as _from .splitters import __file__ as _from .standard import __file__ as _from .stream import __file__ as _from .stream_operators import __file__ as _2 unmodified linesfrom .system_prompts import __file__ as _from .task import __file__ as _from .templates import __file__ as _from .text2sql_utils import __file__ as _from .text_utils import __file__ as _from .type_utils import __file__ as _from .types import __file__ as _
8 unmodified lines910111213141520 unmodified lines36373839404114 unmodified lines5657585960616289 unmodified lines15215315415515615715831 unmodified lines190191192193194195196537 unmodified lines7347357367377387397407417427437447457467477487497507517527537547558 unmodified linesfrom datasets import Features, Valuefrom .dataclass import Dataclassfrom .error_utils import Documentation, UnitxtErrorfrom .operator import (InstanceOperator,MultiStreamOperator,20 unmodified linesconstants = get_constants()def nan_mean(scores):result = mean(score for score in scores if score == score)14 unmodified linesyield {**original, "prediction": prediction}def process(self, predictions: List[str], references: Iterable, split_name: str = "all") -> MultiStream:return MultiStream({89 unmodified linessubset_stream_name = (stream_name+ "://"+ "/".join(instance[self.subsets_field][: self.subset_depth]))31 unmodified lines@lru_cache(maxsize=None)def stream_name_to_origin_subset_group(stream_name):origin, subset_group = stream_name.split("://")if "?" in subset_group:subset, group = subset_group.split("?")else:537 unmodified linespredictions: List[Any],references: Iterable,flatten: bool = False,split_name: str = "all",calc_confidence_intervals: bool = True,):_reset_env_local_catalogs()register_all_artifacts()recipe = MetricRecipe(calc_confidence_intervals=calc_confidence_intervals)multi_stream = recipe(predictions=predictions, references=references, split_name=split_name)if flatten:operator = FlattenInstances()multi_stream = operator(multi_stream)stream = multi_stream[split_name]return EvaluationResults(stream)8 unmodified lines910111213141520 unmodified lines36373839404142434414 unmodified lines5960616263646566676889 unmodified lines15815916016116216316431 unmodified lines196197198199200201202537 unmodified lines7407417427437447457467477487497507517527537547557567577587597607617628 unmodified linesfrom datasets import Features, Valuefrom .dataclass import Dataclassfrom .error_utils import Documentation, UnitxtError, error_contextfrom .operator import (InstanceOperator,MultiStreamOperator,20 unmodified linesconstants = get_constants()DEFAULT_STREAM_NAME = "all_data"DEFAULT_STREAM_SUBSET_SEPARATOR = ">>"def nan_mean(scores):result = mean(score for score in scores if score == score)14 unmodified linesyield {**original, "prediction": prediction}def process(self,predictions: List[str],references: Iterable,split_name: str = DEFAULT_STREAM_NAME,) -> MultiStream:return MultiStream({89 unmodified linessubset_stream_name = (stream_name+ DEFAULT_STREAM_SUBSET_SEPARATOR+ "/".join(instance[self.subsets_field][: self.subset_depth]))31 unmodified lines@lru_cache(maxsize=None)def stream_name_to_origin_subset_group(stream_name):origin, subset_group = stream_name.split(DEFAULT_STREAM_SUBSET_SEPARATOR)if "?" in subset_group:subset, group = subset_group.split("?")else:537 unmodified linespredictions: List[Any],references: Iterable,flatten: bool = False,split_name: str = DEFAULT_STREAM_NAME,calc_confidence_intervals: bool = True,):_reset_env_local_catalogs()register_all_artifacts()recipe = MetricRecipe(calc_confidence_intervals=calc_confidence_intervals)with error_context(stage="Metric Processing"):multi_stream = recipe(predictions=predictions, references=references, split_name=split_name)if flatten:operator = FlattenInstances()multi_stream = operator(multi_stream)stream = multi_stream[split_name]return EvaluationResults(stream)
7 unmodified lines89101112131427 unmodified lines4243444546474815 unmodified lines646566676869312 unmodified lines38238338438538638738838939039139239339439539639739839940040140240340440540640740840943 unmodified lines4534544554564574589 unmodified lines468469470471472473230 unmodified lines704705706707708709244 unmodified lines954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103643 unmodified lines108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175299 unmodified lines14751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415654870 unmodified lines64366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568261 unmodified line68286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068612 unmodified lines6864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069117 unmodified linesimport warningsfrom abc import ABC, abstractmethodfrom collections import Counter, defaultdictfrom dataclasses import fieldfrom enum import Enumfrom functools import lru_cachefrom typing import (27 unmodified linesOptionalField,)from .deprecation_utils import deprecationfrom .error_utils import Documentation, UnitxtError, UnitxtWarningfrom .inference import (HFPipelineBasedInferenceEngine,InferenceEngine,15 unmodified linesfrom .random_utils import get_seedfrom .settings_utils import get_settingsfrom .stream import MultiStream, Streamfrom .type_utils import isoftype, parse_type_string, to_type_stringfrom .types import ToolCallfrom .utils import deep_copy, recursive_copy, retry_connection_with_exponential_backoff312 unmodified linesreturn intermediatesdef process(self, stream: Stream, stream_name: Optional[str] = None):instances_scores, global_scores = self.compute(stream, stream_name)for i, (instance, instance_scores) in enumerate(zip(stream, instances_scores)):previous_score = instance.get("score", {"global": {}, "instance": {}})if i == 0:for key in global_scores:if is_original_key(key) and key in previous_score["global"]:UnitxtWarning(message=f"Metric '{key}' that has just been evaluated with value {global_scores[key]}, is already recorded "f"to have value {previous_score['global'][key]} by a previous metric evaluation on this instance or stream. "f"To avoid overwriting the existing value, add a score_prefix to the metric name (e.g. score_prefix='my_second_' , "f"which will yield, in this case, a score named: 'my_second_{key}')",additional_info_id=Documentation.MULTIPLE_METRICS_OUTPUTS,)global_scores = {**previous_score["global"], **global_scores}instance_scores = {**previous_score["instance"], **instance_scores}yield {**instance,"score": {"global": global_scores, "instance": instance_scores},}def compute(self, stream: Stream, stream_name: Optional[str] = None):evaluation_inputs_stream = self._instances_stream_to_evaluation_inputs(stream)43 unmodified linesreturn resultclass MeanReduction(DictReduction):def reduce_list(self, lst: List[float]):return nan_mean(lst)9 unmodified linesreturn float(nan_max(lst))class ReductionInstanceMetric(MapReduceMetric[PredictionType, IntermediateType],Generic[PredictionType, IntermediateType],230 unmodified lines}class MetricWithConfidenceInterval(Metric):# The number of resamples used to estimate the confidence intervals of this metric.# Use None to disable confidence interval computation.244 unmodified linesprocess_single_instances = Truedef process(self, stream: Stream, stream_name: Optional[str] = None) -> Generator:references = []predictions = []task_data = []instances = []for instance in stream:instance = self.verify_instance(instance)if "score" not in instance:instance["score"] = {"global": {}, "instance": {}}instance_references, instance_prediction = (instance["references"],instance["prediction"],)references.append(instance_references)predictions.append(instance_prediction)instances.append(instance)instance_task_data = (instance["task_data"] if "task_data" in instance else {})task_data.append(instance_task_data)instance_score = None# for backward compatibilityno_score_value = np.nanif self.process_single_instances:try:instance_score = self._compute([instance_references],[instance_prediction],[instance_task_data],)except:no_score_value = Noneif not instance_score:instance_score = {"score": no_score_value,"score_name": self.main_score,}if isinstance(self.main_score, str):instance_score[self.main_score] = no_score_valueinstance["score"]["instance"].update(self._add_score_prefixes_to_score_dict_and_check_against_existing_scores(instance_score, instance["score"]["instance"]))self._validate_references_and_prediction(references, predictions)global_score = {"num_of_instances": len(instances)}result = self._compute(references, predictions, task_data)global_score.update(self._add_score_prefixes_to_score_dict_and_check_against_existing_scores(result, global_score))if self.ci_scores:score_names = [self._add_score_prefix(score_name) for score_name in self.ci_scores]else:score_names = [global_score["score_name"]]for score_name in score_names:confidence_interval = self.compute_global_confidence_intervals(references, predictions, task_data, score_name)global_score.update(confidence_interval)for instance in instances:self.update_and_adjust_global_score(instance, global_score)yield instancedef _compute(self,43 unmodified linesreturn instancedef process(self, stream: Stream, stream_name: Optional[str] = None) -> Generator:instances = []for instance in stream:self.verify_instance(instance)instance = self.preprocess_instance(instance)instances.append(instance)predictions = [instance["prediction"] for instance in instances]references = [instance["references"] for instance in instances]task_data = [instance["task_data"] if "task_data" in instance else {}for instance in instances]self._validate_references_and_prediction(references, predictions)global_score = {"num_of_instances": len(instances)}# compute the metric over all refs and predsinstance_scores = self.compute(references=references,predictions=predictions,task_data=task_data,)# add the score and score_name fieldsfor instance_score in instance_scores:instance_score["score"] = instance_score[self.main_score]instance_score["score_name"] = self.main_scorefor instance, score in zip(instances, instance_scores):if "score" not in instance:instance["score"] = {"global": {}, "instance": {}}instance["score"]["instance"].update(self._add_score_prefixes_to_score_dict_and_check_against_existing_scores(score, instance["score"]["instance"]))for reduction, fields in self.reduction_map.items():assert (reduction in self.implemented_reductions), f"Reduction {reduction} is not implemented, use one of {self.implemented_reductions}"if reduction == "mean":for field_name in fields:field_name_with_prefix = self._add_score_prefix(field_name)global_score[field_name_with_prefix] = nan_mean([instance["score"]["instance"][field_name_with_prefix]for instance in instances])if field_name == self.main_score:global_score["score"] = global_score[field_name_with_prefix]global_score["score_name"] = self.score_prefix + self.main_scoreci_fields = (list(set(self.ci_scores))if self.ci_scores is not Noneelse [self.main_score])ci_fields_with_prefix = [self._add_score_prefix(ci_field) for ci_field in ci_fields]confidence_interval = self.score_based_confidence_interval(instances=instances, score_names=ci_fields_with_prefix)global_score.update(confidence_interval)if reduction == "weighted_win_rate":for field_name in fields:field_name_with_prefix = self._add_score_prefix(field_name)total_battles = 0wins = 0for instance in instances:s = instance["score"]["instance"][field_name_with_prefix]if s > 0:total_battles += swins += selif s < 0:total_battles += abs(s)else:total_battles += 2wins += 1global_score[field_name_with_prefix] = wins / total_battlesif field_name == self.main_score:global_score["score"] = global_score[field_name_with_prefix]global_score["score_name"] = self.score_prefix + self.main_scorefor instance in instances:self.update_and_adjust_global_score(instance, global_score)yield instance@abstractmethoddef compute(299 unmodified linesassert isinstance(fields["score_fields"], list)def process(self, stream: Stream, stream_name: Optional[str] = None) -> Generator:instance_scores = self.compute_instance_scores(stream)global_score = {"num_of_instances": len(instance_scores)}for reduction_type, reduction_params in self.reduction_map.items():assert (reduction_type in self.implemented_reductions), f"Reduction {reduction_type} is not implemented, use one of {self.implemented_reductions}"field_name_full_prefix = ""# used for passing to the bootstrapping, depends on whether the groups are fixed or notaggregation_function = Noneif reduction_type == "mean":aggregation_function = self.average_item_scoresreduction_fields = list(set(reduction_params))# no group reduction, so resample instances individuallyscores_to_resample = instance_scoreselif reduction_type == "max":aggregation_function = self.max_item_scoresreduction_fields = list(set(reduction_params))# no group reduction, so resample instances individuallyscores_to_resample = instance_scoreselif reduction_type == "group_mean":aggregation_function = self.average_item_scoresself._validate_group_mean_reduction()reduction_fields = ([self.main_score]if "score_fields" not in reduction_paramselse list(set(reduction_params["score_fields"])))aggregation_function_name = str(reduction_params["agg_func"][0])field_name_full_prefix = "group_" + aggregation_function_name + "_"do_resample_as_group = reduction_params["agg_func"][2]if do_resample_as_group:# append fixed_ to name because resamples the groups as fixed unitsfield_name_full_prefix = "fixed_" + field_name_full_prefix(scores_to_resample,aggregation_function,) = self._set_up_group_mean_aggregation(instance_scores,reduction_params,reduction_fields,)else:raise ValueError(f"Reduction {reduction_type} is not supported, please specify a valid reduction method in reduction_map {self.reduction_map}.")# calculate global scores for each reduction fieldfor field_name in reduction_fields:field_name_full = (field_name_full_prefix + self.score_prefix + field_name)# if group resampling (3rd element of agg_func parameter) is True, then# 1. scores_to_resample are the group scores, and# 2. aggregation_function is to take the raw mean# if no group resampling (3rd element of agg_func parameter) is False, then# 1. scores_to_resample are the original instance scores, and# 2. aggregation_function is to apply the group aggregation from the instance scores# either way, the application of aggregation_function to scores_to_resample yields the global scoreglobal_score[field_name_full] = aggregation_function(scores_to_resample, self.score_prefix + field_name)if field_name == self.main_score:global_score["score"] = global_score[field_name_full]global_score["score_name"] = field_name_full# need to specify which fields should have CIs calculated for them through ci_scores# (will not automatically calculate CIs for fields in reduction map)if self.ci_scores is not None:confidence_interval = self.score_based_confidence_interval(instances=scores_to_resample,score_names=[self.score_prefix + ci_score for ci_score in set(self.ci_scores)],ci_score_prefix=field_name_full_prefix,aggregation_func=aggregation_function,)global_score.update(confidence_interval)for instance in instance_scores:self.update_and_adjust_global_score(instance, global_score)for i, instance in enumerate(stream):instance["score"] = recursive_copy(instance_scores[i]["score"])yield instancedef compute_instance_scores(self, stream: Stream, stream_name: Optional[str] = None4870 unmodified lines}class SQLExecutionAccuracy(InstanceMetric):reduction_map = {"mean": ["execution_accuracy","non_empty_execution_accuracy","subset_non_empty_execution_result","non_empty_gold_df","gold_sql_runtime","predicted_sql_runtime","pred_to_gold_runtime_ratio","gold_error","predicted_error",]}main_score = "non_empty_execution_accuracy"ci_scores = ["execution_accuracy","non_empty_execution_accuracy","subset_non_empty_execution_result","gold_sql_runtime","predicted_sql_runtime",]prediction_type = "Any" # string representation is comparedsql_timeout = 30.0_requirements_list = ["sqlglot", "func_timeout"]@staticmethoddef compare_dfs_ignore_colnames_ordered_rows(df1, df2):"""Compares two DataFrames based on row content, ignoring column names.Args:df1 (pd.DataFrame): Pandas DataFrame 1 to compare.df2 (pd.DataFrame): Pandas DataFrame 2 to compare.Returns:True if the DataFrames have the same ordered rows (ignoring column names),False otherwise."""df1.fillna(0, inplace=True)df2.fillna(0, inplace=True)# Compare row counts first for a quick checkif df1.shape != df2.shape:return False# Convert DataFrames to numpy arrays of strings to handle mixed typesdf1_array = df1.values.astype(str)df2_array = df2.values.astype(str)# Sort each row's elements (column order independence)df1_sorted_rows = np.array([np.sort(row) for row in df1_array])df2_sorted_rows = np.array([np.sort(row) for row in df2_array])# Compare the sorted rows in orderreturn np.array_equal(df1_sorted_rows, df2_sorted_rows)@staticmethoddef compare_dfs_ignore_colnames_unordered_rows(df1, df2):"""Compares two DataFrames based on row content, ignoring row order and column names.Args:df1 (pd.DataFrame): Pandas DataFrame 1 to compare.df2 (pd.DataFrame): Pandas DataFrame 2 to compare.Returns:True if the DataFrames have the same content (ignoring column names and row order),False otherwise."""# Compare shapes early onif df1.shape != df2.shape:return False# Convert DataFrames to numpy arrays of strings (to handle mixed data types)df1_array = df1.values.astype(str)df2_array = df2.values.astype(str)# Sort columns first, then sort rowsdf1_sorted = np.sort(np.sort(df1_array, axis=1), axis=0)df2_sorted = np.sort(np.sort(df2_array, axis=1), axis=0)# Compare the sorted arraysreturn np.array_equal(df1_sorted, df2_sorted)@staticmethoddef compare_dfs_ignore_colnames_subset(df1, df2, ignore_row_order=True):"""Checks if the values of either DataFrame are a subset of the values in the other DataFrame.Comparison is column order independent, and could optionally be row order independent.We interpret "subset" as follows:- For each row in df1, there must be a matching (or superset) row in df2, i.e. the set of valuesin the df1 row is a subset of the set of values in that df2 row. Then do the same check in reverse.- If either condition (df1 is subset of df2 OR df2 is subset of df1) is satisfied, return True.We treat an empty dataframe as a subset of nothing, while in theory is a subset of any dataframe.Args:df1 (pd.DataFrame): Pandas DataFrame 1 to compare.df2 (pd.DataFrame): Pandas DataFrame 2 to compare.ignore_row_order (bool): If True, row order doesn't matter; if False, row order is respected.Returns:bool: True if df1 is a subset of df2 or vice versa, based on the specified row-order condition."""df1_array = df1.values.astype(str)df2_array = df2.values.astype(str)df1_sorted_rows = [np.sort(row) for row in df1_array]df2_sorted_rows = [np.sort(row) for row in df2_array]def row_is_subset(r_small, r_big):"""Check if all elements of r_small are in r_big."""return set(r_small).issubset(set(r_big))def df_is_subset_of_another(rows_small, rows_big, respect_order):"""Check if the rows_small is subset of rows_big under the given order condition."""if not rows_small:return False # DataFrame needs to be non-empty# If row order matters:if respect_order:i, j = 0, 0while i < len(rows_small) and j < len(rows_big):if row_is_subset(rows_small[i], rows_big[j]):i += 1j += 1return i == len(rows_small)# Row order doesn't matter:matched_indices = set()for r_small in rows_small:found_match = Falsefor idx, r_big in enumerate(rows_big):if idx not in matched_indices and row_is_subset(r_small, r_big):found_match = Truematched_indices.add(idx)breakif not found_match:return Falsereturn Truedf1_sub_df2 = df_is_subset_of_another(df1_sorted_rows, df2_sorted_rows, not ignore_row_order)df2_sub_df1 = df_is_subset_of_another(df2_sorted_rows, df1_sorted_rows, not ignore_row_order)return df1_sub_df2 or df2_sub_df1def get_sql_execution_results(self, predicted_sql: str, gold_sql: str, connector) -> (int, int, int, int, int, int, int, int, int, str, str, str):"""Runs SQL queries using the provided connector and gets scores and results.Args:predicted_sql (str): predicted SQL querygold_sql (str): gold reference SQL queryconnector: database connectorReturns:a 12-tuple of1. execution_result: if df responses match2. non_empty_execution_result: if dfs are non-empty and match3. subset_non_empty_execution_result: if non-empty dfs and one is a subset of the other4. non_empty_gold_df: if gt df is non-empty5. gold_sql_runtime: ground truth query runtime6. predicted_sql_runtime: predicted query runtime7. pred_to_gold_runtime_ratio: ratio of predicted query runtime to gt query runtime8. gold_error: if gt has an error9. predicted_error: if predicted query has an error10. ground truth dataframe11. predicted query's dataframe12. error message (if any)"""import timefrom func_timeout import func_timeoutfrom func_timeout.exceptions import FunctionTimedOutfrom .sql_utils import sqlglot_optimized_equivalencegold_res = Nonegold_error = ""gold_sql_runtime = 0try:start_time = time.perf_counter()gold_res, gold_error = func_timeout(self.sql_timeout,connector.execute_query,args=(gold_sql,),)end_time = time.perf_counter()gold_sql_runtime = end_time - start_timeexcept FunctionTimedOut as e:pred_error = f"Timeout error executing gold SQL: {e}"logger.warning(pred_error)except Exception as e:gold_error = f"Error executing gold SQL: {e}"if gold_error is not None:return (0,0,0,0,gold_sql_runtime,0,0,0,0,"","",gold_error,)if isinstance(gold_res, dict) and "results" in gold_res:gold_res = gold_res["results"]gold_df = pd.DataFrame(gold_res)non_empty_gold_df = 0 if gold_df.empty else 1no_execution_match_result = (1,non_empty_gold_df,non_empty_gold_df,non_empty_gold_df,gold_sql_runtime,0,0,0,0,gold_df.to_json(),"","",)if predicted_sql.lower().strip() == gold_sql.lower().strip():return no_execution_match_resulttry:if sqlglot_optimized_equivalence(gold_sql, predicted_sql):return no_execution_match_resultexcept Exception as e: # Catch specific exceptions if possiblelogger.info(f"Couldn't test equivalent_sqls: {e}. Treating as non-equivalent and going to test with the db.")pred_res = Nonepred_error = ""pred_sql_runtime = 0try:start_time = time.perf_counter()pred_res, pred_error = func_timeout(self.sql_timeout,connector.execute_query,args=(predicted_sql,),)end_time = time.perf_counter()pred_sql_runtime = end_time - start_timeexcept FunctionTimedOut as e:pred_error = f"Timeout error executing predicted SQL: {e}"logger.info(pred_error)except Exception as e:pred_error = f"Error executing predicted SQL: {e}"logger.info(pred_error)pred_to_gold_runtime_ratio = (float(pred_sql_runtime) / gold_sql_runtime if gold_sql_runtime > 0 else 0)if pred_res is None:return (0,0,0,0,gold_sql_runtime,pred_sql_runtime,pred_to_gold_runtime_ratio,0,1,"","",pred_error,)if isinstance(pred_res, dict) and "results" in pred_res:pred_res = pred_res["results"]predicted_df = pd.DataFrame(pred_res)subset_non_empty_execution_result = 0non_empty_execution_result = 0if "ORDER BY" in gold_sql.upper():execution_result = (1if self.compare_dfs_ignore_colnames_ordered_rows(predicted_df, gold_df)else 0)if non_empty_gold_df:if execution_result == 1:non_empty_execution_result = 1if self.compare_dfs_ignore_colnames_subset(gold_df, predicted_df, ignore_row_order=False):subset_non_empty_execution_result = 1else:execution_result = (1if self.compare_dfs_ignore_colnames_unordered_rows(predicted_df, gold_df)else 0)if non_empty_gold_df:if execution_result == 1:non_empty_execution_result = 1if self.compare_dfs_ignore_colnames_subset(gold_df, predicted_df, ignore_row_order=True):subset_non_empty_execution_result = 1return (execution_result,non_empty_execution_result,subset_non_empty_execution_result,non_empty_gold_df,gold_sql_runtime,pred_sql_runtime,pred_to_gold_runtime_ratio,0,0,gold_df.to_json(),predicted_df.to_json(),pred_error,)def compute(self, references: List[Any], prediction: str, task_data: Dict) -> dict:from .sql_utils import get_db_connectorpredicted_sql = predictionexecution_result: float = 0.0if predicted_sql and predicted_sql.strip() != "":if not predicted_sql.startswith("SELECT") and "SELECT" in predicted_sql:predicted_sql = predicted_sql[predicted_sql.find("SELECT") :]if ";" in predicted_sql:predicted_sql = predicted_sql[: predicted_sql.find(";") + 1]db_connector = get_db_connector(task_data["db"]["db_type"])(task_data["db"])logger.debug(f"Starting to get SQL execution results over DB: {task_data['db']}")(execution_result,non_empty_execution_result,subset_non_empty_execution_result,non_empty_gold_df,gold_sql_runtime,predicted_sql_runtime,pred_to_gold_runtime_ratio,gold_error,predicted_error,gold_df_json,predicted_df_json,error_message,) = self.get_sql_execution_results(predicted_sql, references[0], db_connector)result = {"execution_accuracy": float(execution_result),"non_empty_execution_accuracy": float(non_empty_execution_result),"subset_non_empty_execution_result": float(subset_non_empty_execution_result),"non_empty_gold_df": float(non_empty_gold_df),"gold_sql_runtime": float(gold_sql_runtime),"predicted_sql_runtime": float(predicted_sql_runtime),"pred_to_gold_runtime_ratio": float(pred_to_gold_runtime_ratio),"gold_error": float(gold_error),"predicted_error": float(predicted_error),"error_message": str(error_message),"gold_df_json": str(gold_df_json),"predicted_df_json": str(predicted_df_json),}result["score"] = result[self.main_score]result["score_name"] = self.main_scorelogger.debug(f"SQL Execution Accuracy Result: {result}")1 unmodified lineclass SQLNonExecutionAccuracy(InstanceMetric):reduction_map = {"mean": ["sqlglot_validity","sqlparse_validity","sqlglot_equivalence","sqlglot_optimized_equivalence","sqlparse_equivalence","sql_exact_match","sql_syntactic_equivalence",]}main_score = "sqlglot_equivalence"ci_scores = ["sqlglot_validity","sqlparse_validity","sqlglot_equivalence","sqlglot_optimized_equivalence","sqlparse_equivalence","sql_exact_match","sql_syntactic_equivalence",]prediction_type = "Any" # string representation is compared_requirements_list = ["sqlglot", "sqlparse"]def compute(self, references: List[Any], prediction: str, task_data: Dict) -> dict:from .sql_utils import (is_sqlglot_parsable,is_sqlparse_parsable,sql_exact_match,2 unmodified linessqlparse_queries_equivalent,)predicted_sql = predictiongold_sql = references[0]if predicted_sql and predicted_sql.strip() != "":if not predicted_sql.startswith("SELECT") and "SELECT" in predicted_sql:predicted_sql = predicted_sql[predicted_sql.find("SELECT") :]if ";" in predicted_sql:predicted_sql = predicted_sql[: predicted_sql.find(";") + 1]is_sqlglot_parsable = is_sqlglot_parsable(predicted_sql)is_sqlparse_parsable = is_sqlparse_parsable(predicted_sql)result = {"sqlglot_validity": float(is_sqlglot_parsable),"sqlparse_validity": float(is_sqlparse_parsable),"sqlglot_equivalence": float(sqlglot_parsed_queries_equivalent(predicted_sql, gold_sql)if is_sqlglot_parsableelse 0),"sqlglot_optimized_equivalence": float(sqlglot_optimized_equivalence(predicted_sql, gold_sql)if is_sqlglot_parsableelse 0),"sqlparse_equivalence": float(sqlparse_queries_equivalent(predicted_sql, gold_sql)if is_sqlparse_parsableelse 0),"sql_exact_match": float(sql_exact_match(predicted_sql, gold_sql)),}result["sql_syntactic_equivalence"] = float(any(result[key]for key in ["sqlglot_equivalence","sqlglot_optimized_equivalence","sqlparse_equivalence","sql_exact_match",]))logger.debug(f"SQL Non Execution Accuracy Result: {result}")result["score"] = result[self.main_score]result["score_name"] = self.main_score7 unmodified lines8910111213141527 unmodified lines434445464748495015 unmodified lines66676869707172312 unmodified lines38538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841943 unmodified lines4634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045059 unmodified lines515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605230 unmodified lines836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887244 unmodified lines113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121943 unmodified lines126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367299 unmodified lines16671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217634870 unmodified lines6634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467351 unmodified line67376738673967406741674267436744674567466747674867496750675167526753675467556756675767582 unmodified lines6761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468057 unmodified linesimport warningsfrom abc import ABC, abstractmethodfrom collections import Counter, defaultdictfrom dataclasses import asdict, fieldfrom dataclasses import fields as dataclasses_fieldsfrom enum import Enumfrom functools import lru_cachefrom typing import (27 unmodified linesOptionalField,)from .deprecation_utils import deprecationfrom .dict_utils import dict_getfrom .error_utils import Documentation, UnitxtError, UnitxtWarning, error_contextfrom .inference import (HFPipelineBasedInferenceEngine,InferenceEngine,15 unmodified linesfrom .random_utils import get_seedfrom .settings_utils import get_settingsfrom .stream import MultiStream, Streamfrom .text2sql_utils import SQLExecutionResult, SQLNonExecutionMetricResultfrom .type_utils import isoftype, parse_type_string, to_type_stringfrom .types import ToolCallfrom .utils import deep_copy, recursive_copy, retry_connection_with_exponential_backoff312 unmodified linesreturn intermediatesdef process(self, stream: Stream, stream_name: Optional[str] = None):with error_context(self,stage="Evaluating Metric",help="https://www.unitxt.ai/en/latest/docs/adding_metric.html",):instances_scores, global_scores = self.compute(stream, stream_name)for i, (instance, instance_scores) in enumerate(zip(stream, instances_scores)):previous_score = instance.get("score", {"global": {}, "instance": {}})if i == 0:for key in global_scores:if is_original_key(key) and key in previous_score["global"]:UnitxtWarning(message=f"Metric '{key}' that has just been evaluated with value {global_scores[key]}, is already recorded "f"to have value {previous_score['global'][key]} by a previous metric evaluation on this instance or stream. "f"To avoid overwriting the existing value, add a score_prefix to the metric name (e.g. score_prefix='my_second_' , "f"which will yield, in this case, a score named: 'my_second_{key}')",additional_info_id=Documentation.MULTIPLE_METRICS_OUTPUTS,)global_scores = {**previous_score["global"], **global_scores}instance_scores = {**previous_score["instance"], **instance_scores}yield {**instance,"score": {"global": global_scores, "instance": instance_scores},}def compute(self, stream: Stream, stream_name: Optional[str] = None):evaluation_inputs_stream = self._instances_stream_to_evaluation_inputs(stream)43 unmodified linesreturn resultclass GroupReduction(AggregationReduction[Tuple[str, Dict[str, float]]]):def reduce_list(self, lst: List[Tuple[str, float]]):passdef reduce(self, intermidates: Tuple[str, Dict[str, float]]):lists = {}for id, intermidate in intermidates:for key, val in intermidate.items():if key not in lists:lists[key] = []lists[key].append((id, val))result = {}for key, val_list in lists.items():result[key] = self.reduce_list(val_list)return resultclass GroupMean(GroupReduction):def reduce_list(self, lst: List[Tuple[str, float]]):return nan_mean([item[1] for item in lst])class SequentialSuccess(GroupReduction):threshold: float = 0.5def reduce_list(self, lst: List[Tuple[str, float]]):sorted_items = [item for _, item in sorted(lst, key=lambda x: x[0])]successful = 0for item in sorted_items:if item > self.threshold:successful += 1else:breakreturn successful / len(lst)class MeanReduction(DictReduction):def reduce_list(self, lst: List[float]):return nan_mean(lst)9 unmodified linesreturn float(nan_max(lst))class GroupMetric(MapReduceMetric[PredictionType, IntermediateType],Generic[PredictionType, IntermediateType],):main_score: str = Nonemetric: MapReduceMetric[PredictionType, IntermediateType]group_id_field: stritem_id_field: strin_group_reduction: GroupReduction = GroupMean()cross_group_reduction: GroupReduction = GroupMean()n_resamples = Nonedef _get_group_id(self, task_data) -> str:return str(dict_get(task_data, self.group_id_field))def _get_item_id(self, task_data) -> str:return str(dict_get(task_data, self.item_id_field))def prepare(self):super().prepare()self.main_score = self.metric.main_scoredef map_stream(self,evaluation_inputs_stream: Generator[EvaluationInput[PredictionType], None, None],) -> List[Tuple[IntermediateType, str, str]]:group_ids: List[str] = []item_ids: List[str] = []def multi_turn_stream(evaluation_inputs_stream: Generator[EvaluationInput[PredictionType], None, None],) -> Generator[Tuple[PredictionType, List[PredictionType], Dict[str, Any]], None, None]:for prediction, references, task_data in evaluation_inputs_stream:group_ids.append(self._get_group_id(task_data))item_ids.append(self._get_item_id(task_data))yield prediction, references, task_dataintermediates: List[IntermediateType] = list(self.metric.map_stream(multi_turn_stream(evaluation_inputs_stream)))return list(zip(intermediates, group_ids, item_ids))def reduce_group(self, dialog_data: Dict[str, Dict[str, Any]]):return self.in_group_reduction.reduce(list(dialog_data.items()))def reduce_one(self, intermidate: Tuple[IntermediateType, str, str]):return self.metric.reduce_one(intermidate[0])def reduce(self, intermediates: List[Tuple[IntermediateType, str, str]]) -> Dict[str, Any]:data: Dict[str, Dict[str, Any]] = {}for intermediate, group_id, item_id in intermediates:if group_id not in data:data[group_id] = {}data[group_id][item_id] = self.metric.reduce_one(intermediate)group_scores: Dict[str, Dict[str, Any]] = {dialog_id: self.reduce_group(dialog_data)for dialog_id, dialog_data in data.items()}return self.cross_group_reduction.reduce(list(group_scores.items()))class MultiTurnMetric(GroupMetric[PredictionType, IntermediateType],Generic[PredictionType, IntermediateType],):group_id_field = "conversation/id"item_id_field = "conversation/dialog"def _get_item_id(self, task_data):return "assistant_turn_" + str(len(dict_get(task_data, self.item_id_field)) // 2)class ReductionInstanceMetric(MapReduceMetric[PredictionType, IntermediateType],Generic[PredictionType, IntermediateType],230 unmodified lines}class MultiTurnToolCallingMetric(ReductionInstanceMetric[str, Dict[str, float]]):"""Compares each predicted tool call with list of references tool call."""main_score = "argument_schema_validation"reduction = MeanReduction()prediction_type = List[ToolCall]_requirements_list = ["jsonschema-rs"]def prepare(self):super().prepare()import jsonschema_rsself._schema = jsonschema_rsdef map(self,prediction: List[ToolCall],references: List[List[ToolCall]],task_data: Dict[str, Any],) -> Dict[str, float]:validation_scores = []for tool_call in prediction:parameters = Nonefor tool in task_data["__tools__"]:if tool["function"]["name"] == tool_call["name"]:parameters = tool["function"]["parameters"]if parameters is None:validation_scores.append(0.0)else:try:self._schema.validate(parameters,tool_call["arguments"],)validation_scores.append(1.0)except self._schema.ValidationError:validation_scores.append(0.0)argument_schema_validation = sum(validation_scores) / len(validation_scores)return {"argument_schema_validation": argument_schema_validation,}class MetricWithConfidenceInterval(Metric):# The number of resamples used to estimate the confidence intervals of this metric.# Use None to disable confidence interval computation.244 unmodified linesprocess_single_instances = Truedef process(self, stream: Stream, stream_name: Optional[str] = None) -> Generator:with error_context(self,stage="Evaluating Metric",help="https://www.unitxt.ai/en/latest/docs/adding_metric.html",):references = []predictions = []task_data = []instances = []for instance in stream:instance = self.verify_instance(instance)if "score" not in instance:instance["score"] = {"global": {}, "instance": {}}instance_references, instance_prediction = (instance["references"],instance["prediction"],)references.append(instance_references)predictions.append(instance_prediction)instances.append(instance)instance_task_data = (instance["task_data"] if "task_data" in instance else {})task_data.append(instance_task_data)instance_score = None# for backward compatibilityno_score_value = np.nanif self.process_single_instances:try:instance_score = self._compute([instance_references],[instance_prediction],[instance_task_data],)except:no_score_value = Noneif not instance_score:instance_score = {"score": no_score_value,"score_name": self.main_score,}if isinstance(self.main_score, str):instance_score[self.main_score] = no_score_valueinstance["score"]["instance"].update(self._add_score_prefixes_to_score_dict_and_check_against_existing_scores(instance_score, instance["score"]["instance"]))self._validate_references_and_prediction(references, predictions)global_score = {"num_of_instances": len(instances)}result = self._compute(references, predictions, task_data)global_score.update(self._add_score_prefixes_to_score_dict_and_check_against_existing_scores(result, global_score))if self.ci_scores:score_names = [self._add_score_prefix(score_name) for score_name in self.ci_scores]else:score_names = [global_score["score_name"]]for score_name in score_names:confidence_interval = self.compute_global_confidence_intervals(references, predictions, task_data, score_name)global_score.update(confidence_interval)for instance in instances:self.update_and_adjust_global_score(instance, global_score)yield instancedef _compute(self,43 unmodified linesreturn instancedef process(self, stream: Stream, stream_name: Optional[str] = None) -> Generator:with error_context(self,stage="Evaluating Metrics",help="https://www.unitxt.ai/en/latest/docs/adding_metric.html",):instances = []for instance in stream:self.verify_instance(instance)instance = self.preprocess_instance(instance)instances.append(instance)predictions = [instance["prediction"] for instance in instances]references = [instance["references"] for instance in instances]task_data = [instance["task_data"] if "task_data" in instance else {}for instance in instances]self._validate_references_and_prediction(references, predictions)global_score = {"num_of_instances": len(instances)}# compute the metric over all refs and predsinstance_scores = self.compute(references=references,predictions=predictions,task_data=task_data,)# add the score and score_name fieldsfor instance_score in instance_scores:instance_score["score"] = instance_score[self.main_score]instance_score["score_name"] = self.main_scorefor instance, score in zip(instances, instance_scores):if "score" not in instance:instance["score"] = {"global": {}, "instance": {}}instance["score"]["instance"].update(self._add_score_prefixes_to_score_dict_and_check_against_existing_scores(score, instance["score"]["instance"]))for reduction, fields in self.reduction_map.items():assert (reduction in self.implemented_reductions), f"Reduction {reduction} is not implemented, use one of {self.implemented_reductions}"if reduction == "mean":for field_name in fields:field_name_with_prefix = self._add_score_prefix(field_name)global_score[field_name_with_prefix] = nan_mean([instance["score"]["instance"][field_name_with_prefix]for instance in instances])if field_name == self.main_score:global_score["score"] = global_score[field_name_with_prefix]global_score["score_name"] = (self.score_prefix + self.main_score)ci_fields = (list(set(self.ci_scores))if self.ci_scores is not Noneelse [self.main_score])ci_fields_with_prefix = [self._add_score_prefix(ci_field) for ci_field in ci_fields]confidence_interval = self.score_based_confidence_interval(instances=instances, score_names=ci_fields_with_prefix)global_score.update(confidence_interval)if reduction == "weighted_win_rate":for field_name in fields:field_name_with_prefix = self._add_score_prefix(field_name)total_battles = 0wins = 0for instance in instances:s = instance["score"]["instance"][field_name_with_prefix]if s > 0:total_battles += swins += selif s < 0:total_battles += abs(s)else:total_battles += 2wins += 1global_score[field_name_with_prefix] = wins / total_battlesif field_name == self.main_score:global_score["score"] = global_score[field_name_with_prefix]global_score["score_name"] = (self.score_prefix + self.main_score)for instance in instances:self.update_and_adjust_global_score(instance, global_score)yield instance@abstractmethoddef compute(299 unmodified linesassert isinstance(fields["score_fields"], list)def process(self, stream: Stream, stream_name: Optional[str] = None) -> Generator:with error_context(self,stage="Evaluating Metrics",help="https://www.unitxt.ai/en/latest/docs/adding_metric.html",):instance_scores = self.compute_instance_scores(stream)global_score = {"num_of_instances": len(instance_scores)}for reduction_type, reduction_params in self.reduction_map.items():assert (reduction_type in self.implemented_reductions), f"Reduction {reduction_type} is not implemented, use one of {self.implemented_reductions}"field_name_full_prefix = ""# used for passing to the bootstrapping, depends on whether the groups are fixed or notaggregation_function = Noneif reduction_type == "mean":aggregation_function = self.average_item_scoresreduction_fields = list(set(reduction_params))# no group reduction, so resample instances individuallyscores_to_resample = instance_scoreselif reduction_type == "max":aggregation_function = self.max_item_scoresreduction_fields = list(set(reduction_params))# no group reduction, so resample instances individuallyscores_to_resample = instance_scoreselif reduction_type == "group_mean":aggregation_function = self.average_item_scoresself._validate_group_mean_reduction()reduction_fields = ([self.main_score]if "score_fields" not in reduction_paramselse list(set(reduction_params["score_fields"])))aggregation_function_name = str(reduction_params["agg_func"][0])field_name_full_prefix = "group_" + aggregation_function_name + "_"do_resample_as_group = reduction_params["agg_func"][2]if do_resample_as_group:# append fixed_ to name because resamples the groups as fixed unitsfield_name_full_prefix = "fixed_" + field_name_full_prefix(scores_to_resample,aggregation_function,) = self._set_up_group_mean_aggregation(instance_scores,reduction_params,reduction_fields,)else:raise ValueError(f"Reduction {reduction_type} is not supported, please specify a valid reduction method in reduction_map {self.reduction_map}.")# calculate global scores for each reduction fieldfor field_name in reduction_fields:field_name_full = (field_name_full_prefix + self.score_prefix + field_name)# if group resampling (3rd element of agg_func parameter) is True, then# 1. scores_to_resample are the group scores, and# 2. aggregation_function is to take the raw mean# if no group resampling (3rd element of agg_func parameter) is False, then# 1. scores_to_resample are the original instance scores, and# 2. aggregation_function is to apply the group aggregation from the instance scores# either way, the application of aggregation_function to scores_to_resample yields the global scoreglobal_score[field_name_full] = aggregation_function(scores_to_resample, self.score_prefix + field_name)if field_name == self.main_score:global_score["score"] = global_score[field_name_full]global_score["score_name"] = field_name_full# need to specify which fields should have CIs calculated for them through ci_scores# (will not automatically calculate CIs for fields in reduction map)if self.ci_scores is not None:confidence_interval = self.score_based_confidence_interval(instances=scores_to_resample,score_names=[self.score_prefix + ci_scorefor ci_score in set(self.ci_scores)],ci_score_prefix=field_name_full_prefix,aggregation_func=aggregation_function,)global_score.update(confidence_interval)for instance in instance_scores:self.update_and_adjust_global_score(instance, global_score)for i, instance in enumerate(stream):instance["score"] = recursive_copy(instance_scores[i]["score"])yield instancedef compute_instance_scores(self, stream: Stream, stream_name: Optional[str] = None4870 unmodified lines}class SQLExecutionLogicAccuracy(InstanceMetric):sql_timeout: float = 60.0prediction_type = "Any"_requirements_list = ["sqlglot", "func_timeout"]main_score = "non_empty_execution_accuracy"all_metrics = [f.namefor f in dataclasses_fields(SQLExecutionResult)if isinstance(f.type, type) and f.type in (int, float)]reduction_map = {"mean": all_metrics}ci_scores = ["execution_accuracy","non_empty_execution_accuracy","subset_non_empty_execution_accuracy","execution_accuracy_bird","gold_sql_runtime","predicted_sql_runtime",]def compute(self, references: List[Any], prediction: str, task_data: Dict) -> dict:from .text2sql_utils import (ALL_DIALECTS,extract_sql_from_text,get_db_connector,get_sql_execution_results,replace_select_clause,)predicted_sql = extract_sql_from_text(prediction)gold_sql = references[0]dialect = task_data["db"]["db_type"]if dialect not in ALL_DIALECTS:dialect = Nonerevised_sql = (replace_select_clause(gold_sql, predicted_sql, dialect)if gold_sql and predicted_sqlelse "")db_connector = get_db_connector(task_data["db"]["db_type"])(task_data["db"])result_obj = get_sql_execution_results(revised_sql, gold_sql, db_connector, self.sql_timeout)result = asdict(result_obj)result["score"] = result[self.main_score]result["score_name"] = self.main_scorelogger.debug(f"SQL Execution Accuracy Result: {result}")return resultclass SQLExecutionAccuracy(InstanceMetric):sql_timeout: float = 60.0prediction_type = "Any"_requirements_list = ["sqlglot", "func_timeout"]main_score = "non_empty_execution_accuracy"all_metrics = [f.namefor f in dataclasses_fields(SQLExecutionResult)if isinstance(f.type, type) and f.type in (int, float)]reduction_map = {"mean": all_metrics}ci_scores = ["execution_accuracy","non_empty_execution_accuracy","subset_non_empty_execution_accuracy","execution_accuracy_bird","gold_sql_runtime","predicted_sql_runtime",]def compute(self, references: List[Any], prediction: str, task_data: Dict) -> dict:from .text2sql_utils import (extract_sql_from_text,get_db_connector,get_sql_execution_results,)predicted_sql = extract_sql_from_text(prediction)gold_sql = references[0]db_connector = get_db_connector(task_data["db"]["db_type"])(task_data["db"])result_obj = get_sql_execution_results(predicted_sql, gold_sql, db_connector, self.sql_timeout)result = asdict(result_obj)result["score"] = result[self.main_score]result["score_name"] = self.main_scorelogger.debug(f"SQL Execution Accuracy Result: {result}")1 unmodified lineclass SQLNonExecutionAccuracy(InstanceMetric):all_metrics = [f.namefor f in dataclasses_fields(SQLNonExecutionMetricResult)if isinstance(f.type, type) and f.type in (int, float)]reduction_map = {"mean": all_metrics}main_score = "sqlglot_equivalence"ci_scores = all_metricsprediction_type = "Any" # string representation is compared_requirements_list = ["sqlglot", "sqlparse"]def compute(self, references: List[Any], prediction: str, task_data: Dict) -> dict:from .text2sql_utils import (extract_sql_from_text,is_sqlglot_parsable,is_sqlparse_parsable,sql_exact_match,2 unmodified linessqlparse_queries_equivalent,)gold_sql = references[0]predicted_sql = extract_sql_from_text(prediction)is_sqlglot_parsable = is_sqlglot_parsable(predicted_sql)is_sqlparse_parsable = is_sqlparse_parsable(predicted_sql)result_obj = SQLNonExecutionMetricResult(sqlglot_validity=int(is_sqlglot_parsable),sqlparse_validity=int(is_sqlparse_parsable),sqlglot_equivalence=int(sqlglot_parsed_queries_equivalent(predicted_sql, gold_sql)if is_sqlglot_parsableelse 0),sqlglot_optimized_equivalence=int(sqlglot_optimized_equivalence(predicted_sql, gold_sql)if is_sqlglot_parsableelse 0),sqlparse_equivalence=int(sqlparse_queries_equivalent(predicted_sql, gold_sql)if is_sqlparse_parsableelse 0),sql_exact_match=int(sql_exact_match(predicted_sql, gold_sql)),sql_syntactic_equivalence=0, # will update below)result_obj.sql_syntactic_equivalence = int(any([result_obj.sqlglot_equivalence,result_obj.sqlglot_optimized_equivalence,result_obj.sqlparse_equivalence,result_obj.sql_exact_match,]))result = asdict(result_obj)logger.debug(f"SQL Non Execution Accuracy Result: {result}")result["score"] = result[self.main_score]result["score_name"] = self.main_score
5 unmodified lines67891011334 unmodified lines34634734834935035135231 unmodified lines38438538638738838939039139239339439546 unmodified lines4424434444454464474484494504514524534544554564574585 unmodified linesfrom .artifact import Artifactfrom .dataclass import FinalField, InternalField, NonPositionalFieldfrom .settings_utils import get_constantsfrom .stream import DynamicStream, EmptyStreamError, MultiStream, Stream334 unmodified linesdef _process_stream(self, stream: Stream, stream_name: Optional[str] = None) -> Generator:yield from self.process(stream, stream_name)@abstractmethoddef process(self, stream: Stream, stream_name: Optional[str] = None) -> Generator:31 unmodified linesself, stream: Stream, stream_name: Optional[str] = None) -> Generator:page = []for instance in stream:page.append(instance)if len(page) >= self.page_size:yield from self.process(page, stream_name)page = []yield from self._process_page(page, stream_name)def _process_page(self, page: List[Dict], stream_name: Optional[str] = None46 unmodified linesdef _process_stream(self, stream: Stream, stream_name: Optional[str] = None) -> Generator:try:_index = Nonefor _index, instance in enumerate(stream):yield self._process_instance(instance, stream_name)except Exception as e:if _index is None:raise eelse:raise ValueError(f"Error processing instance '{_index}' from stream '{stream_name}' in {self.__class__.__name__} due to the exception above.") from edef _process_instance(self, instance: Dict[str, Any], stream_name: Optional[str] = None5 unmodified lines6789101112334 unmodified lines34734834935035135235335431 unmodified lines38638738838939039139239339439539639739839940040140240340440540640740840941041141241346 unmodified lines4604614624634644654664674685 unmodified linesfrom .artifact import Artifactfrom .dataclass import FinalField, InternalField, NonPositionalFieldfrom .error_utils import error_contextfrom .settings_utils import get_constantsfrom .stream import DynamicStream, EmptyStreamError, MultiStream, Stream334 unmodified linesdef _process_stream(self, stream: Stream, stream_name: Optional[str] = None) -> Generator:with error_context(self, stream=stream_name):yield from self.process(stream, stream_name)@abstractmethoddef process(self, stream: Stream, stream_name: Optional[str] = None) -> Generator:31 unmodified linesself, stream: Stream, stream_name: Optional[str] = None) -> Generator:page = []page_number = 0for instance in stream:page.append(instance)if len(page) >= self.page_size:with error_context(self,stream=stream_name,page=page_number,page_size=len(page),):yield from self.process(page, stream_name)page = []page_number += 1if page: # Handle any remaining instances in the last partial pagewith error_context(self,stream=stream_name,page=page_number,page_size=len(page),final_page=True,):yield from self._process_page(page, stream_name)def _process_page(self, page: List[Dict], stream_name: Optional[str] = None46 unmodified linesdef _process_stream(self, stream: Stream, stream_name: Optional[str] = None) -> Generator:for _index, instance in enumerate(stream):with error_context(self, stream=stream_name, instance=_index):yield self._process_instance(instance, stream_name)def _process_instance(self, instance: Dict[str, Any], stream_name: Optional[str] = None
66 unmodified lines67686970717273235 unmodified lines309310311312313314315120 unmodified lines43643743843944044179 unmodified lines5215225235245255265274 unmodified lines5325335345355365375385395405415421 unmodified line54454554654754854955055155255355455555655755851 unmodified lines610611612613614615616617618619620579 unmodified lines120012011202120312041205120612071208227 unmodified lines1436143714381439144014411442378 unmodified lines18211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187466 unmodified linesfrom .dataclass import NonPositionalField, OptionalFieldfrom .deprecation_utils import deprecationfrom .dict_utils import dict_delete, dict_get, dict_set, is_subpathfrom .error_utils import UnitxtErrorfrom .generator_utils import ReusableGeneratorfrom .operator import (InstanceOperator,235 unmodified linesif not isinstance(item, dict) and item not in value_remove]elif isinstance(value, dict):pass # Skip or handle dict values if neededelif value in value_remove:keys_to_delete.append(key)elif value in value_map:120 unmodified linesfield_to_field: Optional[Union[List[List[str]], Dict[str, str]]] = Noneuse_query: Optional[bool] = Noneprocess_every_value: bool = Falseget_default: Any = Nonenot_exist_ok: bool = Falsenot_exist_do_nothing: bool = False79 unmodified lines) -> Dict[str, Any]:self.verify_field_definition()for from_field, to_field in self._field_to_field:try:old_value = dict_get(instance,from_field,4 unmodified linesif self.not_exist_do_nothing:continueold_value = self.get_defaultexcept Exception as e:raise ValueError(f"Failed to get '{from_field}' from instance due to the exception above.") from etry:if self.process_every_value:new_value = [self.process_instance_value(value, instance)1 unmodified line]else:new_value = self.process_instance_value(old_value, instance)except Exception as e:raise ValueError(f"Failed to process field '{from_field}' from instance due to the exception above.") from edict_set(instance,to_field,new_value,not_exist_ok=True,)return instance51 unmodified linesreturn res@deprecation(version="2.0.0", alternative=Rename)class RenameFields(Rename):passclass AddConstant(FieldOperator):"""Adds a constant, being argument 'add', to the processed value.579 unmodified lines) -> Dict[str, Any]:operator_names = instance.get(self.operators_field)if operator_names is None:assert (self.default_operators is not None), f"No operators found in field '{self.operators_field}', and no default operators provided."operator_names = self.default_operatorsif isinstance(operator_names, str):227 unmodified linesdef process(self, instance: Dict[str, Any], stream_name: Optional[str] = None) -> Dict[str, Any]:instance[self.to_field] = self.compute_expression(instance)return instance378 unmodified lines# to be populated only when two or more metricsaccumulated_scores = []first_instance = stream.peek()metric_names = first_instance.get(self.metric_field, [])if not metric_names:raise RuntimeError(f"Missing metric names in field '{self.metric_field}' and instance '{first_instance}'.")if isinstance(metric_names, str):metric_names = [metric_names]metrics_list = []for metric_name in metric_names:metric = self.get_artifact(metric_name)if isinstance(metric, MetricsList):metrics_list.extend(list(metric.items))elif isinstance(metric, Metric):metrics_list.append(metric)else:raise ValueError(f"Operator {metric_name} must be a Metric or MetricsList")for metric in metrics_list:metric.set_confidence_interval_calculation(self.calc_confidence_intervals)# Each metric operator computes its score and then sets the main score, overwriting# the previous main score value (if any). So, we need to reverse the order of the listed metrics.# This will cause the first listed metric to run last, and the main score will be set# by the first listed metric (as desired).metrics_list = list(reversed(metrics_list))for i, metric in enumerate(metrics_list):if i == 0: # first metricmulti_stream = MultiStream({"tmp": stream})else: # metrics with previous scoresreusable_generator = ReusableGenerator(generator=update_scores_of_stream_instances,gen_kwargs={"stream": stream, "scores": accumulated_scores},)multi_stream = MultiStream.from_generators({"tmp": reusable_generator})multi_stream = metric(multi_stream)if i < len(metrics_list) - 1: # last metricaccumulated_scores = []for inst in multi_stream["tmp"]:accumulated_scores.append(recursive_copy(inst["score"]))yield from multi_stream["tmp"]66 unmodified lines67686970717273235 unmodified lines309310311312313314315316317120 unmodified lines43843944044144244344479 unmodified lines5245255265275285295304 unmodified lines5355365375385395405415421 unmodified line54454554654754854955055155255355455555651 unmodified lines608609610611612613614615616617618619620621622623624625626627628629630631632633634635636579 unmodified lines1216121712181219122012211222122312241225227 unmodified lines1453145414551456145714581459378 unmodified lines183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189566 unmodified linesfrom .dataclass import NonPositionalField, OptionalFieldfrom .deprecation_utils import deprecationfrom .dict_utils import dict_delete, dict_get, dict_set, is_subpathfrom .error_utils import UnitxtError, error_contextfrom .generator_utils import ReusableGeneratorfrom .operator import (InstanceOperator,235 unmodified linesif not isinstance(item, dict) and item not in value_remove]elif isinstance(value, dict):recursive_key_value_replace(value, target_key, value_map, value_remove)elif value in value_remove:keys_to_delete.append(key)elif value in value_map:120 unmodified linesfield_to_field: Optional[Union[List[List[str]], Dict[str, str]]] = Noneuse_query: Optional[bool] = Noneprocess_every_value: bool = Falseset_every_value: bool = NonPositionalField(default=False)get_default: Any = Nonenot_exist_ok: bool = Falsenot_exist_do_nothing: bool = False79 unmodified lines) -> Dict[str, Any]:self.verify_field_definition()for from_field, to_field in self._field_to_field:with error_context(self, field=from_field, action="Read Field"):old_value = dict_get(instance,from_field,4 unmodified linesif self.not_exist_do_nothing:continueold_value = self.get_defaultwith error_context(self, field=from_field, action="Process Field"):if self.process_every_value:new_value = [self.process_instance_value(value, instance)1 unmodified line]else:new_value = self.process_instance_value(old_value, instance)dict_set(instance,to_field,new_value,not_exist_ok=True,set_multiple=self.set_every_value,)return instance51 unmodified linesreturn resclass Move(InstanceOperator):field: strto_field: strdef process(self, instance: Dict[str, Any], stream_name: Optional[str] = None) -> Dict[str, Any]:value = dict_get(instance, self.field)dict_delete(instance, self.field)dict_set(instance, self.to_field, value=value)return instance@deprecation(version="2.0.0", alternative=Rename)class RenameFields(Rename):passclass BytesToString(FieldOperator):def process_value(self, value: Any) -> Any:return str(value)class AddConstant(FieldOperator):"""Adds a constant, being argument 'add', to the processed value.579 unmodified lines) -> Dict[str, Any]:operator_names = instance.get(self.operators_field)if operator_names is None:if self.default_operators is None:raise ValueError(f"No operators found in field '{self.operators_field}', and no default operators provided.")operator_names = self.default_operatorsif isinstance(operator_names, str):227 unmodified linesdef process(self, instance: Dict[str, Any], stream_name: Optional[str] = None) -> Dict[str, Any]:dict_set(instance, self.to_field, self.compute_expression(instance))return instance378 unmodified lines# to be populated only when two or more metricsaccumulated_scores = []with error_context(self, stage="Load Metrics"):first_instance = stream.peek()metric_names = first_instance.get(self.metric_field, [])if not metric_names:raise RuntimeError(f"Missing metric names in field '{self.metric_field}' and instance '{first_instance}'.")if isinstance(metric_names, str):metric_names = [metric_names]metrics_list = []for metric_name in metric_names:metric = self.get_artifact(metric_name)if isinstance(metric, MetricsList):metrics_list.extend(list(metric.items))elif isinstance(metric, Metric):metrics_list.append(metric)else:raise ValueError(f"Operator {metric_name} must be a Metric or MetricsList")with error_context(self, stage="Setup Metrics"):for metric in metrics_list:metric.set_confidence_interval_calculation(self.calc_confidence_intervals)# Each metric operator computes its score and then sets the main score, overwriting# the previous main score value (if any). So, we need to reverse the order of the listed metrics.# This will cause the first listed metric to run last, and the main score will be set# by the first listed metric (as desired).metrics_list = list(reversed(metrics_list))for i, metric in enumerate(metrics_list):if i == 0: # first metricmulti_stream = MultiStream({"tmp": stream})else: # metrics with previous scoresreusable_generator = ReusableGenerator(generator=update_scores_of_stream_instances,gen_kwargs={"stream": stream, "scores": accumulated_scores},)multi_stream = MultiStream.from_generators({"tmp": reusable_generator})multi_stream = metric(multi_stream)if i < len(metrics_list) - 1: # last metricaccumulated_scores = []for inst in multi_stream["tmp"]:accumulated_scores.append(recursive_copy(inst["score"]))yield from multi_stream["tmp"]
97 unmodified lines9899100101102103182 unmodified lines28628728828929029129297 unmodified linesreturn ""class ListToEmptyEntitiesTuples(FieldOperator):def process_value(self, lst: Any) -> Any:try:182 unmodified linesclass ExtractMtBenchRatingJudgment(FieldOperator):def process_value(self, text: Any) -> Any:match = re.search(r"\[\[([\d]+\.?[\d]*)\]\]", text)try:return float(match.group(1)) / 10except:97 unmodified lines9899100101102103104105106107108109110111112113182 unmodified lines29629729829930030130297 unmodified linesreturn ""class GroupDictWithRegex(FieldOperator):pattern: strdef process_value(self, value: Any) -> Any:match = re.match(self.pattern, value)if match:return match.groupdict()return {}class ListToEmptyEntitiesTuples(FieldOperator):def process_value(self, lst: Any) -> Any:try:182 unmodified linesclass ExtractMtBenchRatingJudgment(FieldOperator):def process_value(self, text: Any) -> Any:match = re.search(r"\[\[([\s*\d]+\.?[\d]*\s*)(/\s*10)?\s*\]\]", text)try:return float(match.group(1)) / 10except:
58 unmodified lines5960616263646558 unmodified linesdef load_chat_source(chat_str):chat = json.loads(chat_str)for turn in chat:if isinstance(turn["content"], list):for content in turn["content"]:if content["type"] == "image_url":content["image_url"]["url"] = ImageDataString(58 unmodified lines5960616263646558 unmodified linesdef load_chat_source(chat_str):chat = json.loads(chat_str)for turn in chat:if "content" in turn and isinstance(turn["content"], list):for content in turn["content"]:if content["type"] == "image_url":content["image_url"]["url"] = ImageDataString(
8 unmodified lines9101112131460 unmodified lines75767778798081143 unmodified lines2252262272282292302318 unmodified linesfrom .settings_utils import get_constantsfrom .type_utils import isoftype, to_type_stringfrom .types import (Dialog,Document,Image,60 unmodified linesdef serialize(self, value: Dialog, instance: Dict[str, Any]) -> str:# Convert the Dialog into a string representation, typically combining roles and contentreturn "\n".join(f"{turn['role']}: {turn['content']}" for turn in value)class NumberSerializer(SingleTypeSerializer):143 unmodified linesserialized_type = SQLDatabasedef serialize(self, value: SQLDatabase, instance: Dict[str, Any]) -> str:from .sql_utils import get_db_connectorconnector = get_db_connector(value["db_type"])(value)return connector.get_table_schema()8 unmodified lines910111213141560 unmodified lines76777879808182838485868788899091929394959697143 unmodified lines2412422432442452462478 unmodified linesfrom .settings_utils import get_constantsfrom .type_utils import isoftype, to_type_stringfrom .types import (Conversation,Dialog,Document,Image,60 unmodified linesdef serialize(self, value: Dialog, instance: Dict[str, Any]) -> str:# Convert the Dialog into a string representation, typically combining roles and contentturns = []for turn in value:turn_str = f"{turn['role']}: "if "content" in turn:turn_str += str(turn["content"])if "tool_calls" in turn:turn_str += "\n" + json.dumps(turn["tool_calls"])turns.append(turn_str)return "\n".join(turns)class ConversationSerializer(DialogSerializer):serialized_type = Conversationdef serialize(self, value: Conversation, instance: Dict[str, Any]) -> str:return super().serialize(value["dialog"], instance)class NumberSerializer(SingleTypeSerializer):143 unmodified linesserialized_type = SQLDatabasedef serialize(self, value: SQLDatabase, instance: Dict[str, Any]) -> str:from .text2sql_utils import get_db_connectorconnector = get_db_connector(value["db_type"])(value)return connector.get_table_schema()
123456170 unmodified lines177178179180181182import importlib.metadataimport importlib.utilimport osfrom contextlib import contextmanagerfrom .version import version170 unmodified linesconstants.dataset_url = "unitxt/data"constants.metric_url = "unitxt/metric"constants.version = versionconstants.catalog_hierarchy_sep = "."constants.env_local_catalogs_paths_sep = ":"constants.non_registered_files = [1234567170 unmodified lines178179180181182183184185186import importlib.metadataimport importlib.utilimport osimport sysfrom contextlib import contextmanagerfrom .version import version170 unmodified linesconstants.dataset_url = "unitxt/data"constants.metric_url = "unitxt/metric"constants.version = versionconstants.python = (f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}")constants.catalog_hierarchy_sep = "."constants.env_local_catalogs_paths_sep = ":"constants.non_registered_files = [
22 unmodified lines232425262728725 unmodified lines75475575675775875976076176276376411 unmodified lines77677777877978078122 unmodified lines{"key1": "value1", "key2": value2, "key3": "value3"}"""import jsonimport randomfrom abc import ABC, abstractmethod725 unmodified linesreturn json.loads(value, strict=False)class ToolCallPostProcessor(FieldOperator):failure_value: Any = Noneallow_failure: bool = Falsedef process_value(self, value: str) -> ToolCall:if self.allow_failure:try:result = json.loads(value)11 unmodified linesreturn resultclass DumpJson(FieldOperator):def process_value(self, value: str) -> str:return json.dumps(value)22 unmodified lines23242526272829725 unmodified lines75575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379411 unmodified lines80680780880981081181281381481581681781881982082182282382482582682782882983022 unmodified lines{"key1": "value1", "key2": value2, "key3": "value3"}"""import astimport jsonimport randomfrom abc import ABC, abstractmethod725 unmodified linesreturn json.loads(value, strict=False)class PythonCallProcessor(FieldOperator):def process_value(self, value: str) -> ToolCall:expr = ast.parse(value, mode="eval").bodyfunction = expr.func.idargs = {}for kw in expr.keywords:args[kw.arg] = ast.literal_eval(kw.value)# Handle positional args, if anyif expr.args:args["_args"] = [ast.literal_eval(arg) for arg in expr.args]return {"name": function, "arguments": args}def extract_possible_json_str(text):"""Extract potential JSON string from text by finding outermost braces/brackets."""# Find first opening delimiterstart_positions = [pos for pos in [text.find("{"), text.find("[")] if pos != -1]start = min(start_positions) if start_positions else 0# Find last closing delimiterend_positions = [pos for pos in [text.rfind("}"), text.rfind("]")] if pos != -1]end = max(end_positions) if end_positions else len(text) - 1return text[start : end + 1]class ToolCallPostProcessor(FieldOperator):failure_value: Any = Noneallow_failure: bool = Falsedef process_value(self, value: str) -> ToolCall:value = extract_possible_json_str(value) # clear tokens such as <tool_call> focusing on the call json itselfif self.allow_failure:try:result = json.loads(value)11 unmodified linesreturn resultclass MultipleToolCallPostProcessor(FieldOperator):failure_value: Any = Noneallow_failure: bool = Falsedef process_value(self, value: str) -> List[ToolCall]:if self.allow_failure:try:result = json.loads(value)except json.JSONDecodeError:return self.failure_valueelse:result = json.loads(value, strict=False)if isoftype(result, List[ToolCall]):return resultif not isoftype(result, ToolCall):return self.failure_valuereturn [result]class DumpJson(FieldOperator):def process_value(self, value: str) -> str:return json.dumps(value)
2 unmodified lines3456789275 unmodified lines2852862872882892902912922932942952962972 unmodified linesfrom .artifact import fetch_artifactfrom .deprecation_utils import deprecationfrom .error_utils import Documentation, UnitxtError, UnitxtWarningfrom .logging_utils import get_loggerfrom .metrics import MetricsListfrom .operator import InstanceOperator275 unmodified lines) -> Dict[str, Any]:instance = self.set_default_values(instance)verify_required_schema(self.input_fields,instance,class_name="Task",id=self.__id__,description=self.__description__,)input_fields = {key: instance[key] for key in self.input_fields.keys()}data_classification_policy = instance.get("data_classification_policy", [])2 unmodified lines3456789275 unmodified lines2852862872882892902912922932942952962972982993003013022 unmodified linesfrom .artifact import fetch_artifactfrom .deprecation_utils import deprecationfrom .error_utils import Documentation, UnitxtError, UnitxtWarning, error_contextfrom .logging_utils import get_loggerfrom .metrics import MetricsListfrom .operator import InstanceOperator275 unmodified lines) -> Dict[str, Any]:instance = self.set_default_values(instance)with error_context(self,stage="Schema Verification",help="https://www.unitxt.ai/en/latest/docs/adding_task.html",):verify_required_schema(self.input_fields,instance,class_name="Task",id=self.__id__,description=self.__description__,)input_fields = {key: instance[key] for key in self.input_fields.keys()}data_classification_policy = instance.get("data_classification_policy", [])
5 unmodified lines67891011121314151651 unmodified lines686970717273868 unmodified lines9429439449459469475 unmodified linesfrom .artifact import Artifactfrom .collections import DictCollection, ListCollectionfrom .dataclass import NonPositionalFieldfrom .dict_utils import dict_setfrom .error_utils import Documentation, UnitxtErrorfrom .operator import InstanceOperator, Operatorfrom .random_utils import new_random_generatorfrom .serializers import (DialogSerializer,ImageSerializer,ListSerializer,51 unmodified linesToolCallSerializer(),ToolsSerializer(),DialogSerializer(),ListSerializer(),SQLDatabaseAsSchemaSerializer(),]868 unmodified linesreturn target, referencesdef escape_chars(s, chars_to_escape):for char in chars_to_escape:s = s.replace(char, f"\\{char}")5 unmodified lines6789101112131415161751 unmodified lines69707172737475868 unmodified lines9449459469479489499509519529539549559569579589595 unmodified linesfrom .artifact import Artifactfrom .collections import DictCollection, ListCollectionfrom .dataclass import NonPositionalFieldfrom .dict_utils import dict_get, dict_setfrom .error_utils import Documentation, UnitxtErrorfrom .operator import InstanceOperator, Operatorfrom .random_utils import new_random_generatorfrom .serializers import (ConversationSerializer,DialogSerializer,ImageSerializer,ListSerializer,51 unmodified linesToolCallSerializer(),ToolsSerializer(),DialogSerializer(),ConversationSerializer(),ListSerializer(),SQLDatabaseAsSchemaSerializer(),]868 unmodified linesreturn target, referencesclass MultiTurnTemplate(MultiReferenceTemplate):input_format = ""turns_field: strdef post_process_instance(self, instance):turns = dict_get(instance["input_fields"], self.turns_field)instance["__turns__"] = turnsreturn super().post_process_instance(instance)def escape_chars(s, chars_to_escape):for char in chars_to_escape:s = s.replace(char, f"\\{char}")
6 unmodified lines789101112131415523 unmodified lines539540541542543544150 unmodified lines69569669769869970070111 unmodified lines71371471571671771835 unmodified lines7547557566 unmodified linesimport sqlite3import timefrom abc import ABC, abstractmethodfrom functools import lru_cachefrom typing import Any, List, Optionalimport requestsfrom huggingface_hub import snapshot_downloadfrom requests.exceptions import ConnectionError, ReadTimeout523 unmodified linesreturn connectordef is_sqlglot_parsable(sql: str, db_type="sqlite") -> bool:"""Returns True if sqlglot does not encounter any error, False otherwise."""from sqlglot import parse150 unmodified linesdef sqlparse_queries_equivalent(sql1: str, sql2: str) -> bool:"""Return True if both SQL queries are naively considered equivalent."""try:info1 = extract_select_info(sql1)info2 = extract_select_info(sql2)11 unmodified linesdef sqlglot_parsed_queries_equivalent(sql1: str, sql2: str, dialect: str = "") -> bool:from sqlglot import exp, parse_onetry:35 unmodified linesreturn s.upper()return normalize_sql(sql1) == normalize_sql(sql2)6 unmodified lines78910111213141516171819523 unmodified lines543544545546547548549550551552553554555556557558559150 unmodified lines71071171271371471571611 unmodified lines72872973073173273373435 unmodified lines7707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112426 unmodified linesimport sqlite3import timefrom abc import ABC, abstractmethodfrom collections import Counterfrom dataclasses import dataclassfrom functools import lru_cachefrom typing import Any, List, Optional, Tupleimport numpy as npimport pandas as pdimport requestsfrom huggingface_hub import snapshot_downloadfrom requests.exceptions import ConnectionError, ReadTimeout523 unmodified linesreturn connector@dataclassclass SQLNonExecutionMetricResult:sqlglot_validity: int # Whether SQL parses with sqlglotsqlparse_validity: int # Whether SQL parses with sqlparsesqlglot_equivalence: int # Semantic equivalence using sqlglot ASTsqlglot_optimized_equivalence: int # Equivalence after optimization via sqlglotsqlparse_equivalence: int # Equivalence using sqlparse ASTsql_exact_match: int # Exact string match of predicted and gold SQLsql_syntactic_equivalence: int # Any of the above equivalence conditions holddef is_sqlglot_parsable(sql: str, db_type="sqlite") -> bool:"""Returns True if sqlglot does not encounter any error, False otherwise."""from sqlglot import parse150 unmodified linesdef sqlparse_queries_equivalent(sql1: str, sql2: str) -> bool:"""Returns True if both SQL queries are naively considered equivalent."""try:info1 = extract_select_info(sql1)info2 = extract_select_info(sql2)11 unmodified linesdef sqlglot_parsed_queries_equivalent(sql1: str, sql2: str, dialect: str = "") -> bool:"""Return True if two SQL queries match after parsing with SQLGlot."""from sqlglot import exp, parse_onetry:35 unmodified linesreturn s.upper()return normalize_sql(sql1) == normalize_sql(sql2)@dataclassclass SQLExecutionResult:execution_accuracy: int # Whether the predicted and gold SQL results match exactlynon_empty_execution_accuracy: (int # Same as execution_accuracy but only if gold is non-empty)subset_non_empty_execution_accuracy: (int # Whether predicted is a subset of gold or vice versa, non-empty only)execution_accuracy_bird: (int # Whether the predicted SQL matches gold using BIRD evaluation logic)non_empty_gold_df: int # Whether the gold SQL produced a non-empty dataframegold_sql_runtime: float # Time taken to execute the gold SQLpredicted_sql_runtime: float # Time taken to execute the predicted SQLpred_to_gold_runtime_ratio: float # Ratio of predicted runtime to gold runtimegold_error: int # Whether the gold SQL had an execution errorpredicted_error: int # Whether the predicted SQL had an execution errorgold_df_json: str # JSON representation of the gold SQL result dataframepredicted_df_json: str # JSON representation of the predicted SQL result dataframeerror_message: str # Error message from predicted execution if anydef compare_dfs_ignore_colnames_ordered_rows(df1: pd.DataFrame, df2: pd.DataFrame) -> bool:if df1.shape != df2.shape:return Falsedf1_sorted_rows = np.array([np.sort(row) for row in df1.values.astype(str)])df2_sorted_rows = np.array([np.sort(row) for row in df2.values.astype(str)])return np.array_equal(df1_sorted_rows, df2_sorted_rows)def compare_dfs_ignore_colnames_unordered_rows(df1: pd.DataFrame, df2: pd.DataFrame) -> bool:if df1.shape != df2.shape:return Falsedf1_sorted = np.sort(np.sort(df1.values.astype(str), axis=1), axis=0)df2_sorted = np.sort(np.sort(df2.values.astype(str), axis=1), axis=0)return np.array_equal(df1_sorted, df2_sorted)def compare_dfs_ignore_colnames_subset(df1: pd.DataFrame, df2: pd.DataFrame, ignore_row_order: bool = True) -> bool:"""Checks if the smaller of the two DataFrames is likely a subset of the other.Subset comparison is column-based, to support Text2SQL evaluation for when thepredicted SQL dataframe has missing or additional columns. Each row is treated asa multiset of (stringified) values, and the function checks if every row in thesmaller DataFrame (by column count) is a multiset subset of the corresponding rowin the larger DataFrame. When ground truth SQL does not have ORDER BY,ignore_row_order can be set to True to ignore the order of rows. In this case,column values are sorted before comparison. This means that there could be caseswhere the dataframes have the exact same number of rows and column values aftersort are the same, but the dataframes are not actually a subset of each other.This is unlikely to happen in practice, but the score is not guaranteed to be100% accurate and may overestimate the accuracy.Args:df1 (pd.DataFrame): The first DataFrame to compare.df2 (pd.DataFrame): The second DataFrame to compare.ignore_row_order (bool, optional): If True, ignores the order of rows bysorting them before comparison. Defaults to True.Returns:bool: True if the smaller DataFrame (column-wise) is likely a subset of thelarger one, False otherwise."""def row_to_multiset(row):return Counter(str(x) for x in row)def rows_to_multisets(df):return [row_to_multiset(row) for row in df.values]def sort_df(df):sorted_df = df.copy()for col in sorted_df.columns:sorted_df[col] = sorted_df[col].astype(str).sort_values(ignore_index=True)return sorted_dfif df1.empty or df2.empty or len(df1) != len(df2):return Falsesubset_df, superset_df = (df1, df2) if df1.shape[1] <= df2.shape[1] else (df2, df1)if ignore_row_order:subset_df = sort_df(subset_df)superset_df = sort_df(superset_df)subset_rows = rows_to_multisets(subset_df)superset_rows = rows_to_multisets(superset_df)for r1, r2 in zip(subset_rows, superset_rows):if not all(r1[k] <= r2.get(k, 0) for k in r1):return Falsereturn Truedef compare_dfs_bird_eval_logic(df1: pd.DataFrame, df2: pd.DataFrame):"""Check if two SQL query result sets are exactly equal, as in BIRD evaluation.This function checks if the set of rows returned by the predicted SQL query(`predicted_res`) is exactly equal to the set of rows returned by the ground truthSQL query (`ground_truth_res`). This is the logic used in the original BIRDevaluation code:https://github.com/AlibabaResearch/DAMO-ConvAI/blob/main/bird/llm/src/evaluation.py."""df1_set = {tuple(row) for row in df1.values.astype(str)}df2_set = {tuple(row) for row in df2.values.astype(str)}return int(df1_set == df2_set)def compare_result_dfs(gold_df: pd.DataFrame, pred_df: pd.DataFrame, gold_sql: str) -> Tuple[int, int, int]:"""Compares two DataFrames representing SQL query results.Args:gold_df (pd.DataFrame): The ground truth DataFrame.pred_df (pd.DataFrame): The predicted DataFrame.gold_sql (str): The ground truth SQL query string.Returns:Tuple[int, int, int]: A tuple containing:- match (int): 1 if the predicted DataFrame matches the gold DataFrame- non_empty_match (int): 1 if both DataFrames are non-empty and match,0 otherwise.- subset_match (int): 1 if the predicted DataFrame is a subset orsuperset of the gold DataFrame.Notes:- The comparison ignores column names.- Row order is considered only if 'ORDER BY' is present in the SQL query."""subset_match = 0non_empty_match = 0if "ORDER BY" in gold_sql.upper():match = int(compare_dfs_ignore_colnames_ordered_rows(pred_df, gold_df))if not gold_df.empty and not pred_df.empty:non_empty_match = matchif compare_dfs_ignore_colnames_subset(gold_df, pred_df, ignore_row_order=False):subset_match = 1else:match = int(compare_dfs_ignore_colnames_unordered_rows(pred_df, gold_df))if not gold_df.empty and not pred_df.empty:non_empty_match = matchif compare_dfs_ignore_colnames_subset(gold_df, pred_df, ignore_row_order=True):subset_match = 1return match, non_empty_match, subset_matchdef run_query(sql: str, connector, sql_timeout: float) -> Tuple[Optional[pd.DataFrame], float, str]:"""Executes a SQL query using the provided connector with a timeout.Args:sql (str): The SQL query string to execute.connector: An object with an `execute_query` method that executes the SQLquery.sql_timeout (float): The maximum time in seconds to allow for queryexecution.Returns:Tuple[Optional[pd.DataFrame], float, str]:- A pandas DataFrame containing the query results, or None if an erroroccurred.- The duration in seconds taken to execute the query. 0.0 if an error.- An error message string if an error occurred, otherwise an emptystring.Notes:- If the SQL string is empty or only whitespace, returns immediately with amessage.- If the query execution exceeds the timeout, returns a timeout errormessage.- Any other exceptions are caught and returned as error messages."""import timefrom func_timeout import func_timeoutfrom func_timeout.exceptions import FunctionTimedOutif not sql.strip():return None, 0.0, "No SQL query found in the prediction."try:start = time.perf_counter()result, error = func_timeout(sql_timeout, connector.execute_query, args=(sql,))duration = time.perf_counter() - startif isinstance(result, dict) and "results" in result:result = result["results"]if error:return None, duration, errorreturn pd.DataFrame(result), duration, ""except FunctionTimedOut as e:return None, 0.0, f"Timeout: {e}"except Exception as e:return None, 0.0, f"Error: {e}"def get_sql_execution_results(predicted_sql: str, gold_sql: str, connector, sql_timeout: float) -> SQLExecutionResult:"""Execute and compare predicted and gold SQL queries, returning execution metrics.Args:predicted_sql (str): The SQL query predicted by the model.gold_sql (str): The reference (gold) SQL query.connector: Database connector object used to execute the queries.sql_timeout (float): Maximum time (in seconds) allowed for query execution.Returns:SQLExecutionResult: An object containing various execution metrics, including:- execution_accuracy (int): 1 if predicted and gold queries produceequivalent results, else 0.- non_empty_execution_accuracy (int): 1 if both queries produce non-emptyand equivalent results, else 0.- subset_non_empty_execution_accuracy (int): 1 if predicted results are asubset or superset of gold results and non-empty, else 0. Subsetcomparison is column-based. This means that the predicted SQL dataframecan have missing or additional columns compared to the gold SQL dataframe.- execution_accuracy_bird (int): 1 if results match according to BIRDevaluation logic, else 0.- non_empty_gold_df (int): 1 if the gold query result is non-empty, else 0.- gold_sql_runtime (float): Execution time for the gold SQL query.- predicted_sql_runtime (float): Execution time for the predicted SQL query.- pred_to_gold_runtime_ratio (float): Ratio of predicted to gold queryruntimes.- gold_error (int): 1 if the gold query failed, else 0.- predicted_error (int): 1 if the predicted query failed, else 0.- gold_df_json (str): JSON representation of the gold query resultDataFrame.- predicted_df_json (str): JSON representation of the predicted queryresult DataFrame.- error_message (str): Error message if any query failed, else emptystring.Notes:- If the gold query fails, the function returns early with error details.- If the predicted query is identical or SQL-equivalent to the gold query,results are considered correct without execution.- Otherwise, both queries are executed and their results compared usingmultiple metrics."""gold_df, gold_runtime, gold_error_msg = run_query(gold_sql, connector, sql_timeout)gold_error = int(bool(gold_error_msg))if gold_error:return SQLExecutionResult(execution_accuracy=0,non_empty_execution_accuracy=0,subset_non_empty_execution_accuracy=0,execution_accuracy_bird=0,non_empty_gold_df=0,gold_sql_runtime=gold_runtime,predicted_sql_runtime=0,pred_to_gold_runtime_ratio=0,gold_error=gold_error,predicted_error=0,gold_df_json="",predicted_df_json="",error_message=gold_error_msg,)non_empty_gold_df = int(not gold_df.empty)if predicted_sql.strip().lower() == gold_sql.strip().lower():return SQLExecutionResult(execution_accuracy=1,non_empty_execution_accuracy=non_empty_gold_df,subset_non_empty_execution_accuracy=non_empty_gold_df,execution_accuracy_bird=1,non_empty_gold_df=non_empty_gold_df,gold_sql_runtime=gold_runtime,predicted_sql_runtime=0,pred_to_gold_runtime_ratio=0,gold_error=0,predicted_error=0,gold_df_json=gold_df.to_json(),predicted_df_json=gold_df.to_json(),error_message="",)try:if sqlglot_optimized_equivalence(gold_sql, predicted_sql):return SQLExecutionResult(execution_accuracy=1,non_empty_execution_accuracy=non_empty_gold_df,subset_non_empty_execution_accuracy=non_empty_gold_df,execution_accuracy_bird=1,non_empty_gold_df=non_empty_gold_df,gold_sql_runtime=gold_runtime,predicted_sql_runtime=0,pred_to_gold_runtime_ratio=0,gold_error=0,predicted_error=0,gold_df_json=gold_df.to_json(),predicted_df_json=gold_df.to_json(),error_message="",)except Exception as e:logger.info(f"Could not check SQL equivalence: {e}")pred_df, pred_runtime, pred_error_msg = run_query(predicted_sql, connector, sql_timeout)pred_error = 1 if pred_error_msg else 0if pred_df is None:return SQLExecutionResult(execution_accuracy=0,non_empty_execution_accuracy=0,subset_non_empty_execution_accuracy=0,execution_accuracy_bird=0,non_empty_gold_df=non_empty_gold_df,gold_sql_runtime=gold_runtime,predicted_sql_runtime=pred_runtime,pred_to_gold_runtime_ratio=(pred_runtime / gold_runtime)if gold_runtime > 0else 0,gold_error=0,predicted_error=pred_error,gold_df_json=gold_df.to_json(),predicted_df_json="",error_message=pred_error_msg,)match, non_empty_match, subset_match = compare_result_dfs(gold_df, pred_df, gold_sql)bird_match = compare_dfs_bird_eval_logic(gold_df, pred_df)return SQLExecutionResult(execution_accuracy=match,non_empty_execution_accuracy=non_empty_match,subset_non_empty_execution_accuracy=subset_match,execution_accuracy_bird=bird_match,non_empty_gold_df=non_empty_gold_df,gold_sql_runtime=gold_runtime,predicted_sql_runtime=pred_runtime,pred_to_gold_runtime_ratio=(pred_runtime / gold_runtime)if gold_runtime > 0else 0,gold_error=0,predicted_error=0,gold_df_json=gold_df.to_json(),predicted_df_json=pred_df.to_json(),error_message=pred_error_msg,)def replace_select_clause(source_query: str, target_query: str, dialect: str = "postgres") -> str:"""Replaces the SELECT clause of the target SQL query with the SELECT clause from the source SQL query.Args:source_query (str): SQL query whose SELECT clause will be used.target_query (str): SQL query whose SELECT clause will be replaced.dialect (str): SQL dialect for parsing and rendering (default: "postgres").Returns:str: A new SQL query with the SELECT clause of `target_query` replaced by that of `source_query`.Raises:ValueError: If either query is not a valid SELECT statement.Example:>>> replace_select_clause(... "SELECT id FROM employees",... "SELECT name FROM employees WHERE age > 30"... )"SELECT id FROM employees WHERE age > 30""""from sqlglot import exp, parse_oneif not dialect:dialect = "postgres"# Parse queries using the specified dialectsource_ast = parse_one(source_query, read=dialect)target_ast = parse_one(target_query, read=dialect)if not isinstance(source_ast, exp.Select) or not isinstance(target_ast, exp.Select):raise ValueError("Both queries must be valid SELECT statements.")# Replace SELECT expressions in the target with those from the sourcetarget_ast.set("expressions", source_ast.expressions)# Return the updated SQL string using the dialectreturn target_ast.sql(dialect=dialect)def extract_sql_from_text(text: str) -> str:"""Extracts the first SQL query from the given text.Priority:1. SQL inside fenced blocks like ```sql ... ```2. SQL starting on a new line or after a colon/label3. SQL without semicolonReturns:The SQL query string, or an empty string if not found."""# 1. Look for fenced SQL code blockfenced_block_pattern = re.compile(r"```sql\s+(.*?)```", re.IGNORECASE | re.DOTALL)match = fenced_block_pattern.search(text)if match:return match.group(1).strip()# 2. Inline SQL with semicolonsql_keywords = r"(?:SELECT|INSERT|UPDATE|DELETE|WITH)\s+"sql_start = (r"(?:^|\n|:\s*)" # Start of string, newline, or colon label like "Just run:")sql_pattern = re.compile(rf"{sql_start}({sql_keywords}.*?;)", re.IGNORECASE | re.DOTALL)match = sql_pattern.search(text)if match:return match.group(1).strip()# 3. Inline SQL without semicolonfallback_pattern = re.compile(rf"{sql_start}({sql_keywords}.*)", re.IGNORECASE | re.DOTALL)fallback_match = fallback_pattern.search(text)if fallback_match:return fallback_match.group(1).strip()return ""ALL_DIALECTS = ["Athena","BigQuery","ClickHouse","Databricks","Doris","Drill","Druid","DuckDB","Hive","Materialize","MySQL","Oracle","Postgres","Presto","PRQL","Redshift","RisingWave","Snowflake","Spark","Spark2","SQLite","StarRocks","Tableau","Teradata","Trino","TSQL",]
502 unmodified lines503504505506507508509510511502 unmodified linesif is_typed_dict(typing_type):if not isinstance(object, dict):return Falsefor key, expected_type in typing_type.__annotations__.items():if key not in object or not isoftype(object[key], expected_type):return Falsereturn Trueif typing_type == typing.Any:502 unmodified lines503504505506507508509510511512513514515516517518519520521522523524525526527502 unmodified linesif is_typed_dict(typing_type):if not isinstance(object, dict):return False# Only support total=True, check each fieldfor key, expected_type in typing_type.__annotations__.items():# Check if field is Optional (Union with None)is_optional = (hasattr(expected_type, "__origin__")and expected_type.__origin__ is Unionand type(None) in expected_type.__args__)if key not in object:# Field is missing - only allowed if it's Optionalif not is_optional:return Falseelse:# Field is present - check typeif not isoftype(object[key], expected_type):return Falsereturn Trueif typing_type == typing.Any:
5 unmodified lines6789101112134 unmodified lines1819202122232427 unmodified lines5253545556575859606162636465666768697071727374757677787980818283848586875 unmodified linesNumber = NewType("Number", Union[float, int])class Turn(TypedDict):role: Literal["system", "user", "agent"]content: Text4 unmodified linesis_answerable: boolDialog = NewType("Dialog", List[Turn])class Image(TypedDict):27 unmodified linesdata: Optional[Dict[str, Dict]]class JsonSchema:@classmethoddef __verify_type__(cls, object):if not isinstance(object, dict):return Falseimport jsonschema_rsjsonschema_rs.meta.validate(object)return Trueclass Tool(TypedDict):name: strdescription: strparameters: JsonSchemaclass ToolCall(TypedDict):name: strarguments: Dict[str, Any]register_type(Text)register_type(Number)register_type(Turn)register_type(Dialog)register_type(Table)register_type(Audio)register_type(Image)register_type(Video)register_type(Document)register_type(MultiDocument)register_type(RagResponse)5 unmodified lines67891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556574 unmodified lines62636465666768697071727327 unmodified lines1011021031041051061071081091101111121131141151161175 unmodified linesNumber = NewType("Number", Union[float, int])class JsonSchema:@classmethoddef __verify_type__(cls, object):if not isinstance(object, dict):return Falseimport jsonschema_rsjsonschema_rs.meta.validate(object)return Trueclass Tool(TypedDict):# Original fieldsname: strdescription: strparameters: JsonSchema# LiteLLM extensiontype: Optional[Literal["function"]]class ToolCall(TypedDict):name: strarguments: Dict[str, Any]class ToolCallContext(TypedDict):id: strtype: Literal["function"]function: ToolCallclass ToolCallTurn(TypedDict):role: Literal["assistant"]content: Optional[str]tool_calls: List[ToolCallContext]class ToolOutputTurn(TypedDict):role: Literal["tool"]tool_call_id: strname: strcontent: strclass TextTurn(TypedDict):role: Literal["system", "user", "agent", "assistant"]content: Text4 unmodified linesis_answerable: boolDialog = NewType("Dialog", List[Union[TextTurn, ToolCallTurn, ToolOutputTurn]])class Conversation(TypedDict):id: strdialog: Dialogclass Image(TypedDict):27 unmodified linesdata: Optional[Dict[str, Dict]]register_type(Text)register_type(Number)register_type(TextTurn)register_type(ToolCallTurn)register_type(ToolOutputTurn)register_type(Dialog)register_type(Table)register_type(Audio)register_type(Image)register_type(Video)register_type(Conversation)register_type(Document)register_type(MultiDocument)register_type(RagResponse)
1version = "1.24.0"1version = "1.25.0"
api.py+49-5
artifact.py+28-18
collections_operators.py+60-2
data.py+1-1
dataclass.py+59
dialog_operators.py+10-1
dict_utils.py+1-1
error_utils.py+254-12
evaluate_cli.py+56-3
formats.py+53-9
fusion.py+14-16
inference.py+229-126
llm_as_judge_constants.py+1-2
loaders.py+107-81
metric.py+1-1
metric_utils.py+19-12
metrics.py+548-654
operator.py+23-13
operators.py+79-58
processors.py+11-1
schema.py+1-1
serializers.py+18-2
settings_utils.py+4
struct_data_operators.py+49
task.py+13-8
templates.py+13-1
sql_utils.py → text2sql_utils.pyRenamed+488-2
type_utils.py+18-2
types.py+56-26
version.py+1-1