Upload folder using huggingface_hub
Browse filesFiles changed (16)
- formats.py+5-5
- inference.py+19-2
- llm_as_judge_constants.py+1-1
- llm_as_judge_from_template.py+1
- loaders.py+3-1
- metrics.py+37-38
- operator.py+4
- operators.py+1-1
- schema.py+3-3
- settings_utils.py+3
- standard.py+2-2
- system_prompts.py+4-2
- task.py+8-2
- templates.py+4-4
- text_utils.py+72-2
- version.py+1-1
115 unmodified lines11611711811912012112210 unmodified lines1331341351361371381391401411421431441451463 unmodified lines15015115215315415515662 unmodified lines219220221222223224225115 unmodified linesclass BaseFormat(Format):demos_field: str = "demos"@staticmethoddef _pop_field(instance, field_name, do_pop: bool = True) -> str:10 unmodified linesdef _prepare_instance_fields(self, instance) -> Tuple[str]:instance_fields = {}for field in "source", "instruction", "system_prompt", "target_prefix":instance_fields[field] = self._pop_field(instance, field)instance_fields["media"] = self._pop_field(instance, "media", do_pop=False)if not instance_fields["media"]:instance_fields["media"] = {"images": [], "audios": []}instance_fields["demos"] = []if self.demos_field is not None and self.demos_field in instance:demos = instance[self.demos_field]assert (3 unmodified linesdemo = {}for field in ["source", "target", "target_prefix"]:demo[field] = self._pop_field(demo_instance, field, do_pop=False)instance_fields["demos"].append(demo)return instance_fields62 unmodified lines.. code-block::system_format = SystemFormat(demos_field="demos",demo_format="Input: {source}\nOutput: {target}\n\n",model_input_format="Instruction: {instruction}\n\n{demos}Input: {source}\nOutput: ",)115 unmodified lines11611711811912012112210 unmodified lines1331341351361371381391401411421431441451463 unmodified lines15015115215315415515662 unmodified lines219220221222223224225115 unmodified linesclass BaseFormat(Format):demos_field: str = constants.demos_field@staticmethoddef _pop_field(instance, field_name, do_pop: bool = True) -> str:10 unmodified linesdef _prepare_instance_fields(self, instance) -> Tuple[str]:instance_fields = {}for field in "source", constants.instruction_field, constants.system_prompt_field, "target_prefix":instance_fields[field] = self._pop_field(instance, field)instance_fields["media"] = self._pop_field(instance, "media", do_pop=False)if not instance_fields["media"]:instance_fields["media"] = {"images": [], "audios": []}instance_fields[constants.demos_field] = []if self.demos_field is not None and self.demos_field in instance:demos = instance[self.demos_field]assert (3 unmodified linesdemo = {}for field in ["source", "target", "target_prefix"]:demo[field] = self._pop_field(demo_instance, field, do_pop=False)instance_fields[constants.demos_field].append(demo)return instance_fields62 unmodified lines.. code-block::system_format = SystemFormat(demos_field=constants.demos_field,demo_format="Input: {source}\nOutput: {target}\n\n",model_input_format="Instruction: {instruction}\n\n{demos}Input: {source}\nOutput: ",)
1936 unmodified lines193719381939194019411942543 unmodified lines24862487248824892490249124922493491 unmodified lines29852986298729882989299029911936 unmodified linestime_limit: Optional[int] = Nonetop_p: Optional[float] = Nonen: Optional[int] = NoneCredentialsWML = Dict[543 unmodified lines"of messages.")def to_messages(self, instance: Union[Dict, List]) -> List[List[Dict[str, Any]]]:if isinstance(instance["source"], str) and "media" in instance:return self._create_messages_from_instance(instance)messages = super().to_messages(instance)491 unmodified linesmapping each supported API to a correspondingmodel identifier string. This mapping allows consistent access to modelsacross different API backends.provider_specific_args: (Optional[Dict[str, Dict[str,str]]]) Args specific to a provider for example provider_specific_args={"watsonx": {"max_requests_per_second": 4}}"""label: str = "cross_provider"1936 unmodified lines193719381939194019411942194319441945543 unmodified lines24892490249124922493249424952496249724982499250025012502250325042505250625072508491 unmodified lines3000300130023003300430053006300730081936 unmodified linestime_limit: Optional[int] = Nonetop_p: Optional[float] = Nonen: Optional[int] = Noneseed: Optional[int] = Nonelogit_bias: Optional[Dict[str, Any]] = Nonestop: Optional[List[str]] = NoneCredentialsWML = Dict[543 unmodified lines"of messages.")@staticmethoddef check_instance_contains_image(instance: Dict[str, Any]) -> bool:if "media" not in instance:return Falseif not isinstance(instance["media"], dict):return Falseif "images" not in instance["media"]:return Falseif not instance["media"]["images"]:return Falsereturn Truedef to_messages(self, instance: Union[Dict, List]) -> List[List[Dict[str, Any]]]:if isinstance(instance["source"], str) and self.check_instance_contains_image(instance):return self._create_messages_from_instance(instance)messages = super().to_messages(instance)491 unmodified linesmapping each supported API to a correspondingmodel identifier string. This mapping allows consistent access to modelsacross different API backends.provider_specific_args:(Optional[Dict[str, Dict[str,str]]]) Args specific to a provider for example provider_specific_args={"watsonx": {"max_requests_per_second": 4}}"""label: str = "cross_provider"
204 unmodified lines205206207208209210211204 unmodified lines),CriteriaOption("Pass","There is no numeriselected_providercal temperature reading in the response.",),],{"Yes": 1.0, "No": 0.5, "Pass": 0.0},204 unmodified lines205206207208209210211204 unmodified lines),CriteriaOption("Pass","There is no numerical temperature reading in the response.",),],{"Yes": 1.0, "No": 0.5, "Pass": 0.0},
36 unmodified lines37383940414236 unmodified linesinference_model (InferenceEngine): The module that creates the inference of the judge llm.reduction_map (dict): A dictionary specifying the reduction method for the metric.batch_size (int): The size of the bulk."""main_score: str = "llm_as_judge"36 unmodified lines3738394041424336 unmodified linesinference_model (InferenceEngine): The module that creates the inference of the judge llm.reduction_map (dict): A dictionary specifying the reduction method for the metric.batch_size (int): The size of the bulk."""main_score: str = "llm_as_judge"
442 unmodified lines443444445446447448449450451452453147 unmodified lines601602603604605606607442 unmodified linesdataset = reader(self.files[split], **self.get_args()).to_dict("records")except ValueError:import fsspecwith fsspec.open(self.files[split], mode="rt") as f:dataset = reader(f, **self.get_args()).to_dict("records")except Exception as e:logger.debug(f"Attempt csv load {attempt + 1} failed: {e}")if attempt < settings.loaders_max_retries - 1:147 unmodified linesbucket_name='my-bucket')multi_stream = load_ibm_cloud.process()"""endpoint_url_env: straws_access_key_id_env: str442 unmodified lines443444445446447448449450451452453454455147 unmodified lines603604605606607608609442 unmodified linesdataset = reader(self.files[split], **self.get_args()).to_dict("records")breakexcept ValueError:import fsspecwith fsspec.open(self.files[split], mode="rt") as f:dataset = reader(f, **self.get_args()).to_dict("records")breakexcept Exception as e:logger.debug(f"Attempt csv load {attempt + 1} failed: {e}")if attempt < settings.loaders_max_retries - 1:147 unmodified linesbucket_name='my-bucket')multi_stream = load_ibm_cloud.process()""" # pragma: allowlist secretendpoint_url_env: straws_access_key_id_env: str
74 unmodified lines7576777879802 unmodified lines838485868788899091929394952215 unmodified lines2311231223132314231523162317231823192320232123222323502 unmodified lines28262827282828292830283128322833283450 unmodified lines28852886288728882889289028912892732 unmodified lines362536263627362836293630363130 unmodified lines3662366336643665366636673668196 unmodified lines386538663867386838693870387138723873249 unmodified lines412341244125412641274128412941304131159 unmodified lines429142924293429442954296429710 unmodified lines4308430943104311431243131641 unmodified lines595559565957595859595960307 unmodified lines62686269627062716272627362746275627662776278627962806281628262836284628595 unmodified lines63816382638363846385638657 unmodified lines64446445644664476448644974 unmodified lineswarnings.filterwarnings("ignore", category=DegenerateDataWarning)def hf_evaluate_load(path: str, *args, **kwargs):if settings.hf_offline_metrics_path is not None:path = os.path.join(settings.hf_offline_metrics_path, path)2 unmodified lines*args,**kwargs,experiment_id=str(uuid.uuid4()),download_config=DownloadConfig(max_retries=settings.loaders_max_retries,),verification_mode="no_checks",trust_remote_code=settings.allow_unverified_code,download_mode= "force_redownload" if settings.disable_hf_datasets_cache else "reuse_dataset_if_exists")class MetricsList(ListCollection):def verify(self):2215 unmodified linesDocumentation.HUGGINGFACE_METRICS,)assert (self.hf_additional_input_fields is Noneor isoftype(self.hf_additional_input_fields, List[str])), f"Argument hf_additional_input_fields should be either None or List[str]. It is now: {self.hf_additional_input_fields}."assert (self.hf_additional_input_fields_pass_one_value is Noneor isoftype(self.hf_additional_input_fields_pass_one_value, List[str])), f"Argument hf_additional_input_fields_pass_one_value should be either None or List[str]. It is now: {self.hf_additional_input_fields_pass_one_value}."return super().verify()502 unmodified linesdef prepare(self):super().prepare()self._metric = hf_evaluate_load(self.metric, "multilabel")def add_str_to_id(self, str):if str not in self.str_to_id:50 unmodified lineslabels=labels_param,)if isinstance(result[self.metric], numpy.ndarray):assert (len(result[self.metric]) == len(labels)), f"F1 result ({result[self.metric]}) has more entries than labels ({labels})"final_result = {self.main_score: nan_mean(result[self.metric])}for i, label in enumerate(labels):732 unmodified linesif settings.hf_offline_models_path is not None:model_path = os.path.join(settings.hf_offline_models_path, model_path)self.pipe = pipeline("text-classification", model=model_path, device=device,)def compute(30 unmodified linesmodel_path = os.path.join(settings.hf_offline_models_path, model_path)self.regard_model = AutoModelForSequenceClassification.from_pretrained(model_path,)self.regard_tokenizer = AutoTokenizer.from_pretrained(model_path)196 unmodified linesprediction_type = strreduction_map: Dict[str, List[str]] = Noneopenai_models: List[str] = ["gpt-3.5-turbo"]anthropic_models: List[str] = [] # this is here for the sake of documentation for future modelsmock_models: List[str] = ["mock"]external_api_models = openai_models + anthropic_modelsdata_classification_policy = ["public"]249 unmodified linesmodel_path = self.model_nameif settings.hf_offline_models_path is not None:model_path = os.path.join(settings.hf_offline_models_path, model_path)self.model = (self.model_class().from_pretrained(model_path).to(self.device))self.tokenizer = AutoTokenizer.from_pretrained(model_path)if self.tokenizer.pad_token_id is None:self.tokenizer.pad_token_id = self.tokenizer.eos_token_id159 unmodified linesbatch_size: int = 2model_name: str = "vectara/hallucination_evaluation_model"prediction_type = str# single_reference_per_prediction = Truemax_context_words = 4096reduction_map = {"mean": [main_score]}10 unmodified lineselse:device = "cpu"from transformers import AutoModelForSequenceClassificationmodel_path = self.model_nameif settings.hf_offline_models_path is not None:model_path = os.path.join(settings.hf_offline_models_path, model_path)1641 unmodified linesdef prepare(self):from transformers import AutoTokenizerif not isinstance(self.risk_type, RiskType):self.risk_type = RiskType[self.risk_type]if not hasattr(self, "_tokenizer") or self._tokenizer is None:307 unmodified linesif df1.shape != df2.shape:return False# run over all columns of d11,# and see if there is a columns in df2 that matches it,# if not return False, if all the columns worked return tuefor df1_col in df1.columns:col_matched = Falsefor df2_col in df2.columns:if all(df1[df1_col].values == df2[df2_col].values):col_matched = Trueif not col_matched:return Falsereturn True@staticmethoddef is_subset_ignore_colnames(df1, df2):95 unmodified linesgold_error,)gold_df = pd.DataFrame(gold_res)non_empty_gold_df = 0 if gold_df.empty else 157 unmodified linespred_error,)predicted_df = pd.DataFrame(pred_res)execution_result = (74 unmodified lines757677787980812 unmodified lines848586878889909192939495969798991001012215 unmodified lines23172318231923202321232223232324232523262327502 unmodified lines283028312832283328342835283650 unmodified lines28872888288928902891289228932894732 unmodified lines36273628362936303631363236333634363530 unmodified lines366636673668366936703671196 unmodified lines386838693870387138723873387438753876249 unmodified lines4126412741284129413041314132159 unmodified lines429242934294429542964297429810 unmodified lines43094310431143124313431443151641 unmodified lines5957595859595960596159625963307 unmodified lines627162726273627462756276627762786279628095 unmodified lines6376637763786379638063816382638357 unmodified lines6441644264436444644564466447644874 unmodified lineswarnings.filterwarnings("ignore", category=DegenerateDataWarning)def hf_evaluate_load(path: str, *args, **kwargs):if settings.hf_offline_metrics_path is not None:path = os.path.join(settings.hf_offline_metrics_path, path)2 unmodified lines*args,**kwargs,experiment_id=str(uuid.uuid4()),download_config=DownloadConfig(max_retries=settings.loaders_max_retries,),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"),)class MetricsList(ListCollection):def verify(self):2215 unmodified linesDocumentation.HUGGINGFACE_METRICS,)assert self.hf_additional_input_fields is None or isoftype(self.hf_additional_input_fields, List[str]), f"Argument hf_additional_input_fields should be either None or List[str]. It is now: {self.hf_additional_input_fields}."assert self.hf_additional_input_fields_pass_one_value is None or isoftype(self.hf_additional_input_fields_pass_one_value, List[str]), f"Argument hf_additional_input_fields_pass_one_value should be either None or List[str]. It is now: {self.hf_additional_input_fields_pass_one_value}."return super().verify()502 unmodified linesdef prepare(self):super().prepare()self._metric = hf_evaluate_load(self.metric, "multilabel")def add_str_to_id(self, str):if str not in self.str_to_id:50 unmodified lineslabels=labels_param,)if isinstance(result[self.metric], numpy.ndarray):assert len(result[self.metric]) == len(labels), f"F1 result ({result[self.metric]}) has more entries than labels ({labels})"final_result = {self.main_score: nan_mean(result[self.metric])}for i, label in enumerate(labels):732 unmodified linesif settings.hf_offline_models_path is not None:model_path = os.path.join(settings.hf_offline_models_path, model_path)self.pipe = pipeline("text-classification",model=model_path,device=device,)def compute(30 unmodified linesmodel_path = os.path.join(settings.hf_offline_models_path, model_path)self.regard_model = AutoModelForSequenceClassification.from_pretrained(model_path,)self.regard_tokenizer = AutoTokenizer.from_pretrained(model_path)196 unmodified linesprediction_type = strreduction_map: Dict[str, List[str]] = Noneopenai_models: List[str] = ["gpt-3.5-turbo"]anthropic_models: List[str] = ([]) # this is here for the sake of documentation for future modelsmock_models: List[str] = ["mock"]external_api_models = openai_models + anthropic_modelsdata_classification_policy = ["public"]249 unmodified linesmodel_path = self.model_nameif settings.hf_offline_models_path is not None:model_path = os.path.join(settings.hf_offline_models_path, model_path)self.model = self.model_class().from_pretrained(model_path).to(self.device)self.tokenizer = AutoTokenizer.from_pretrained(model_path)if self.tokenizer.pad_token_id is None:self.tokenizer.pad_token_id = self.tokenizer.eos_token_id159 unmodified linesbatch_size: int = 2model_name: str = "vectara/hallucination_evaluation_model"prediction_type = str# single_reference_per_prediction = Truemax_context_words = 4096reduction_map = {"mean": [main_score]}10 unmodified lineselse:device = "cpu"from transformers import AutoModelForSequenceClassificationmodel_path = self.model_nameif settings.hf_offline_models_path is not None:model_path = os.path.join(settings.hf_offline_models_path, model_path)1641 unmodified linesdef prepare(self):from transformers import AutoTokenizerif not isinstance(self.risk_type, RiskType):self.risk_type = RiskType[self.risk_type]if not hasattr(self, "_tokenizer") or self._tokenizer is None:307 unmodified linesif df1.shape != df2.shape:return Falsedf1_rows_sorted = [sorted(map(str, row)) for row in df1.to_numpy()]df2_rows_sorted = [sorted(map(str, row)) for row in df2.to_numpy()]return df1_rows_sorted == df2_rows_sorted@staticmethoddef is_subset_ignore_colnames(df1, df2):95 unmodified linesgold_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 157 unmodified linespred_error,)if isinstance(pred_res, dict) and "results" in pred_res:pred_res = pred_res["results"]predicted_df = pd.DataFrame(pred_res)execution_result = (
156 unmodified lines15715815916016116286 unmodified lines249250251252253254156 unmodified lines"""class SideEffectOperator(StreamingOperator):"""Base class for operators that does not affect the stream."""86 unmodified linespassclass StreamInitializerOperator(SourceOperator):"""A class representing a stream initializer operator in the streaming system.156 unmodified lines15715815916016116216386 unmodified lines250251252253254255256257258156 unmodified lines"""class SideEffectOperator(StreamingOperator):"""Base class for operators that does not affect the stream."""86 unmodified linespassdef get_splits(self):return list(self.process().keys())class StreamInitializerOperator(SourceOperator):"""A class representing a stream initializer operator in the streaming system.
1526 unmodified lines15271528152915301531153215331526 unmodified linesif not isinstance(self.allowed_values, list):raise ValueError(f"The allowed_field_values is not a type list but '{type(self.allowed_field_values)}'")def process(1526 unmodified lines15271528152915301531153215331526 unmodified linesif not isinstance(self.allowed_values, list):raise ValueError(f"The allowed_values is not a type list but '{type(self.allowed_values)}'")def process(
150 unmodified lines151152153154155156157158159160150 unmodified lines)if "criteria" in task_data and isinstance(task_data["criteria"], Artifact):task_data["criteria"] = self.artifact_to_jsonable(task_data["criteria"])if "demos" in instance:task_data["demos"] = [self._get_instance_task_data(instance)for instance in instance.pop("demos")]instance = self.serialize_instance_fields(instance, task_data)150 unmodified lines151152153154155156157158159160150 unmodified lines)if "criteria" in task_data and isinstance(task_data["criteria"], Artifact):task_data["criteria"] = self.artifact_to_jsonable(task_data["criteria"])if constants.demos_field in instance:task_data[constants.demos_field] = [self._get_instance_task_data(instance)for instance in instance.pop(constants.demos_field)]instance = self.serialize_instance_fields(instance, task_data)
191 unmodified lines192193194195196197191 unmodified linesconstants.instance_stream = "__INSTANCE_STREAM__"constants.image_tag = "unitxt-img"constants.demos_pool_field = "_demos_pool_"def get_settings() -> Settings:191 unmodified lines192193194195196197198199200191 unmodified linesconstants.instance_stream = "__INSTANCE_STREAM__"constants.image_tag = "unitxt-img"constants.demos_pool_field = "_demos_pool_"constants.demos_field = "demos"constants.instruction_field = "instruction"constants.system_prompt_field = "system_prompt"def get_settings() -> Settings:
275 unmodified lines276277278279280281282325 unmodified lines608609610611612613614275 unmodified linesdemos_pool_field_name: str = constants.demos_pool_fielddemos_taken_from: str = "train"demos_field: str = "demos"sampler: Sampler = None# do not push demos to instances whose "demos" field is already populated325 unmodified lines))self.verbalization.steps.append(GetLength(field="demos", to_field="recipe_metadata/num_demos"))self.verbalization.steps.append(Set(275 unmodified lines276277278279280281282325 unmodified lines608609610611612613614275 unmodified linesdemos_pool_field_name: str = constants.demos_pool_fielddemos_taken_from: str = "train"demos_field: str = constants.demos_fieldsampler: Sampler = None# do not push demos to instances whose "demos" field is already populated325 unmodified lines))self.verbalization.steps.append(GetLength(field=constants.demos_field, to_field="recipe_metadata/num_demos"))self.verbalization.steps.append(Set(
2 unmodified lines34567894 unmodified lines141516171819202122232 unmodified linesfrom .dataclass import NonPositionalFieldfrom .operator import InstanceOperatorclass SystemPrompt(InstanceOperator):"""The role of SystemPrompt is to add task-independent opening-text to every instance."""4 unmodified linesself, instance: Dict[str, Any], stream_name: Optional[str] = None) -> Dict[str, Any]:if self.skip_rendered_instance:if "system_prompt" in instance:return instanceinstance["system_prompt"] = self.get_system_prompt(instance)return instance2 unmodified lines345678910114 unmodified lines161718192021222324252 unmodified linesfrom .dataclass import NonPositionalFieldfrom .operator import InstanceOperatorfrom .settings_utils import get_constantsconstants = get_constants()class SystemPrompt(InstanceOperator):"""The role of SystemPrompt is to add task-independent opening-text to every instance."""4 unmodified linesself, instance: Dict[str, Any], stream_name: Optional[str] = None) -> Dict[str, Any]:if self.skip_rendered_instance:if constants.system_prompt_field in instance:return instanceinstance[constants.system_prompt_field] = self.get_system_prompt(instance)return instance
301 unmodified lines302303304305306307308309310301 unmodified lines"media": instance.get("media", {}),"recipe_metadata": instance.get("recipe_metadata", {}),}if "demos" in instance:# for the case of recipe.skip_demoed_instancesresult["demos"] = instance["demos"]if stream_name == constants.inference_stream:return result301 unmodified lines302303304305306307308309310311312313314315316301 unmodified lines"media": instance.get("media", {}),"recipe_metadata": instance.get("recipe_metadata", {}),}if constants.demos_field in instance:# for the case of recipe.skip_demoed_instancesresult[constants.demos_field] = instance[constants.demos_field]if constants.instruction_field in instance:result[constants.instruction_field] = instance[constants.instruction_field]if constants.system_prompt_field in instance:result[constants.system_prompt_field] = instance[constants.system_prompt_field]if stream_name == constants.inference_stream:return result
75 unmodified lines76777879808182838441 unmodified lines12612712812913013113213313413513613713875 unmodified linesself.postprocessors, List[Union[Operator, str]]), f"The template post processors field '{self.postprocessors}' is not a list of processors. Instead it is of type '{to_type_string(type(self.postprocessors))}'."def input_fields_to_instruction_and_target_prefix(self, input_fields):instruction = self.apply_formatting(input_fields, "input field", self.instruction, "instruction")target_prefix = self.apply_formatting(input_fields,41 unmodified linessource = self.input_fields_to_source(serialized_inputs)instruction, target_prefix = self.input_fields_to_instruction_and_target_prefix(serialized_inputs)result = {**instance,"source": source,"instruction": instruction,"target_prefix": target_prefix,"postprocessors": self.postprocessors,}75 unmodified lines76777879808182838441 unmodified lines12612712812913013113213313413513613713875 unmodified linesself.postprocessors, List[Union[Operator, str]]), f"The template post processors field '{self.postprocessors}' is not a list of processors. Instead it is of type '{to_type_string(type(self.postprocessors))}'."def input_fields_to_instruction_and_target_prefix(self, input_fields, instruction):instruction = self.apply_formatting(input_fields, "input field", instruction, "instruction")target_prefix = self.apply_formatting(input_fields,41 unmodified linessource = self.input_fields_to_source(serialized_inputs)instruction, target_prefix = self.input_fields_to_instruction_and_target_prefix(serialized_inputs, instance.get(constants.instruction_field, self.instruction))result = {**instance,"source": source,constants.instruction_field: instruction,"target_prefix": target_prefix,"postprocessors": self.postprocessors,}
200 unmodified lines20120220320420520620728 unmodified lines2362372382392402414 unmodified lines246247248249250251252253254255256200 unmodified linesassert (indent_delta >= 2), f"Needs at least 2 position indentations, for the case of list elements, that are to be preceded each by ' -'. Got indent_delta={indent_delta}."res = [] # conputed hereunder as a list of lines, that are indented only at the endif isinstance(d, dict):if len(d) == 0:28 unmodified linesd1 = f'"{d1}"'return [d1]def print_dict(d, indent=0, indent_delta=4, max_chars=None, keys_to_print=None, log_level="info"4 unmodified linesdef print_dict_as_yaml(d: dict, indent_delta=2) -> str:yaml_lines = construct_dict_as_yaml_lines(d)# yaml_lines = [re.sub(r"(\n+)", r'"\1"', line) for line in yaml_lines]# yaml_lines = [line.replace("\n", "\\n") for line in yaml_lines]return "\n".join(yaml_lines)def nested_tuple_to_string(nested_tuple: tuple) -> str:"""Converts a nested tuple to a string, with elements separated by underscores.200 unmodified lines20120220320420520620728 unmodified lines2362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063074 unmodified lines312313314315316317318319320321322323324325326200 unmodified linesassert (indent_delta >= 2), f"Needs at least 2 position indentations, for the case of list elements, that are to be preceded each by ' -'. Got indent_delta={indent_delta}."res = [] # computed hereunder as a list of lines, that are indented only at the endif isinstance(d, dict):if len(d) == 0:28 unmodified linesd1 = f'"{d1}"'return [d1]def construct_dict_as_python_lines(d, indent_delta=4) -> List[str]:"""Constructs the lines of a dictionary formatted as a piece of python code.Args:d: The element to be formatted.indent_delta (int, optional): The amount of spaces to add for each level of indentation. Defaults to 2."""indent_delta_str = " " * indent_deltares = [] # computed hereunder as a list of lines, that are indented only at the endif isinstance(d, dict):istype = Falseif len(d) == 0:return ["{}"]if "__type__" in d:istype = Trueres = ["__type__" + d["__type__"] + "("]if len(d) == 1:res[0] += ")"return reselse:res = ["{"]for key, val in d.items():if key == "__type__":continueprintable_key = f'"{key}"' if not istype else keyres.append(printable_key + ("=" if istype else ": "))py_for_val = construct_dict_as_python_lines(val, indent_delta=indent_delta)assert len(py_for_val) > 0if len(py_for_val) == 1:res[-1] += (py_for_val[0] +",")else:res[-1] += py_for_val[0]if py_for_val[0].startswith("{") or py_for_val[0].startswith("["):for line in py_for_val[1:-1]:res.append(indent_delta_str + line)else:# val is type, its inner lines are already indentedres.extend(py_for_val[1:-1])res.append(py_for_val[-1]+",")res.append(")" if istype else "}")if istype:for i in range(1,len(res)-1):res[i] = indent_delta_str+res[i]return resif isinstance(d, list):if len(d) == 0:return ["[]"]res = ["["]for val in d:py_for_val = construct_dict_as_python_lines(val, indent_delta=indent_delta)assert len(py_for_val) > 0for line in py_for_val[:-1]:res.append(line)res.append(py_for_val[-1] + ",")res.append("]")return res# d1 = re.sub(r"(\n+)", r'"\1"', str(d))if isinstance(d, str):return [f'"{d}"']if d is None or isinstance (d, (int, float, bool)):return [f"{d}"]raise RuntimeError(f"unrecognized value to print as python: {d}")def print_dict(d, indent=0, indent_delta=4, max_chars=None, keys_to_print=None, log_level="info"4 unmodified linesdef print_dict_as_yaml(d: dict, indent_delta=2) -> str:yaml_lines = construct_dict_as_yaml_lines(d, indent_delta=indent_delta)# yaml_lines = [re.sub(r"(\n+)", r'"\1"', line) for line in yaml_lines]# yaml_lines = [line.replace("\n", "\\n") for line in yaml_lines]return "\n".join(yaml_lines)def print_dict_as_python(d: dict, indent_delta=4) -> str:py_lines = construct_dict_as_python_lines(d, indent_delta=indent_delta)assert len(py_lines)> 0return "\n".join(py_lines)def nested_tuple_to_string(nested_tuple: tuple) -> str:"""Converts a nested tuple to a string, with elements separated by underscores.
1version = "1.19.0"1version = "1.20.0"
formats.py+5-5
inference.py+19-2
llm_as_judge_constants.py+1-1
llm_as_judge_from_template.py+1
loaders.py+3-1
metrics.py+37-38
operator.py+4
operators.py+1-1
schema.py+3-3
settings_utils.py+3
standard.py+2-2
system_prompts.py+4-2
task.py+8-2
templates.py+4-4
text_utils.py+72-2
version.py+1-1