id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
3,975
def get_default_azure_credential(): from azure.identity import DefaultAzureCredential try: from azure.ai.ml._azure_environments import _get_default_cloud_name, EndpointURLS, _get_cloud, AzureEnvironments except ImportError: return DefaultAzureCredential() # Support sovereign cloud cases, like mooncake, fairfax. cloud_name = _get_default_cloud_name() if cloud_name != AzureEnvironments.ENV_DEFAULT: cloud = _get_cloud(cloud=cloud_name) authority = cloud.get(EndpointURLS.ACTIVE_DIRECTORY_ENDPOINT) credential = DefaultAzureCredential(authority=authority, exclude_shared_token_cache_credential=True) else: credential = DefaultAzureCredential() return credential
null
3,976
import re from typing import Any, Dict, Mapping from promptflow._constants import LINE_NUMBER_KEY from promptflow._utils.logger_utils import LoggerFactory from promptflow.batch._errors import InputMappingError The provided code snippet includes necessary dependencies for implementing the `apply_inputs_mapping` function. Write a Python function `def apply_inputs_mapping( inputs: Mapping[str, Mapping[str, Any]], inputs_mapping: Mapping[str, str], ) -> Dict[str, Any]` to solve the following problem: Apply input mapping to inputs for new contract. .. admonition:: Examples .. code-block:: python inputs: { "data": {"answer": "I'm fine, thank you.", "question": "How are you?"}, "baseline": {"answer": "The weather is good."}, } inputs_mapping: { "question": "${data.question}", "groundtruth": "${data.answer}", "baseline": "${baseline.answer}", "deployment_name": "literal_value", } Returns: { "question": "How are you?", "groundtruth": "I'm fine, thank you." "baseline": "The weather is good.", "deployment_name": "literal_value", } :param inputs: A mapping of input keys to their corresponding values. :type inputs: Mapping[str, Mapping[str, Any]] :param inputs_mapping: A mapping of input keys to their corresponding mapping expressions. :type inputs_mapping: Mapping[str, str] :return: A dictionary of input keys to their corresponding mapped values. :rtype: Dict[str, Any] :raises InputMappingError: If any of the input mapping relations are not found in the inputs. Here is the function: def apply_inputs_mapping( inputs: Mapping[str, Mapping[str, Any]], inputs_mapping: Mapping[str, str], ) -> Dict[str, Any]: """Apply input mapping to inputs for new contract. .. admonition:: Examples .. code-block:: python inputs: { "data": {"answer": "I'm fine, thank you.", "question": "How are you?"}, "baseline": {"answer": "The weather is good."}, } inputs_mapping: { "question": "${data.question}", "groundtruth": "${data.answer}", "baseline": "${baseline.answer}", "deployment_name": "literal_value", } Returns: { "question": "How are you?", "groundtruth": "I'm fine, thank you." "baseline": "The weather is good.", "deployment_name": "literal_value", } :param inputs: A mapping of input keys to their corresponding values. :type inputs: Mapping[str, Mapping[str, Any]] :param inputs_mapping: A mapping of input keys to their corresponding mapping expressions. :type inputs_mapping: Mapping[str, str] :return: A dictionary of input keys to their corresponding mapped values. :rtype: Dict[str, Any] :raises InputMappingError: If any of the input mapping relations are not found in the inputs. """ result = {} notfound_mapping_relations = [] for map_to_key, map_value in inputs_mapping.items(): # Ignore reserved key configuration from input mapping. if map_to_key == LINE_NUMBER_KEY: continue if not isinstance(map_value, str): # All non-string values are literal values. result[map_to_key] = map_value continue match = re.search(r"^\${([^{}]+)}$", map_value) if match is not None: pattern = match.group(1) # Could also try each pair of key value from inputs to match the pattern. # But split pattern by '.' is one deterministic way. # So, give key with less '.' higher priority. splitted_str = pattern.split(".") find_match = False for i in range(1, len(splitted_str)): key = ".".join(splitted_str[:i]) source = ".".join(splitted_str[i:]) if key in inputs and source in inputs[key]: find_match = True result[map_to_key] = inputs[key][source] break if not find_match: notfound_mapping_relations.append(map_value) else: result[map_to_key] = map_value # Literal value # Return all not found mapping relations in one exception to provide better debug experience. if notfound_mapping_relations: invalid_relations = ", ".join(notfound_mapping_relations) raise InputMappingError( message_format=( "The input for batch run is incorrect. Couldn't find these mapping relations: {invalid_relations}. " "Please make sure your input mapping keys and values match your YAML input section and input data. " "For more information, refer to the following documentation: https://aka.ms/pf/column-mapping" ), invalid_relations=invalid_relations, ) # For PRS scenario, apply_inputs_mapping will be used for exec_line and line_number is not necessary. if LINE_NUMBER_KEY in inputs: result[LINE_NUMBER_KEY] = inputs[LINE_NUMBER_KEY] return result
Apply input mapping to inputs for new contract. .. admonition:: Examples .. code-block:: python inputs: { "data": {"answer": "I'm fine, thank you.", "question": "How are you?"}, "baseline": {"answer": "The weather is good."}, } inputs_mapping: { "question": "${data.question}", "groundtruth": "${data.answer}", "baseline": "${baseline.answer}", "deployment_name": "literal_value", } Returns: { "question": "How are you?", "groundtruth": "I'm fine, thank you." "baseline": "The weather is good.", "deployment_name": "literal_value", } :param inputs: A mapping of input keys to their corresponding values. :type inputs: Mapping[str, Mapping[str, Any]] :param inputs_mapping: A mapping of input keys to their corresponding mapping expressions. :type inputs_mapping: Mapping[str, str] :return: A dictionary of input keys to their corresponding mapped values. :rtype: Dict[str, Any] :raises InputMappingError: If any of the input mapping relations are not found in the inputs.
3,977
import hashlib import os from os import PathLike from pathlib import Path from typing import Union from promptflow._sdk._constants import DAG_FILE_NAME, DEFAULT_ENCODING from promptflow._utils.logger_utils import LoggerFactory from promptflow._utils.yaml_utils import dump_yaml, load_yaml logger = LoggerFactory.get_logger(name=__name__) The provided code snippet includes necessary dependencies for implementing the `get_flow_lineage_id` function. Write a Python function `def get_flow_lineage_id(flow_dir: Union[str, PathLike])` to solve the following problem: Get the lineage id for flow. The flow lineage id will be same for same flow in same GIT repo or device. If the flow locates in GIT repo: use Repo name + relative path to flow_dir as session id Otherwise: use device id + absolute path to flow_dir as session id :param flow_dir: flow directory Here is the function: def get_flow_lineage_id(flow_dir: Union[str, PathLike]): """ Get the lineage id for flow. The flow lineage id will be same for same flow in same GIT repo or device. If the flow locates in GIT repo: use Repo name + relative path to flow_dir as session id Otherwise: use device id + absolute path to flow_dir as session id :param flow_dir: flow directory """ flow_dir = Path(flow_dir).resolve() if not flow_dir.is_dir(): flow_dir = flow_dir.parent try: from git import Repo repo = Repo(flow_dir, search_parent_directories=True) lineage_id = f"{os.path.basename(repo.working_dir)}/{flow_dir.relative_to(repo.working_dir).as_posix()}" logger.debug("Got lineage id %s from git repo.", lineage_id) except Exception: # failed to get repo, use device id + absolute path to flow_dir as session id import uuid device_id = uuid.getnode() lineage_id = f"{device_id}/{flow_dir.absolute().as_posix()}" logger.debug("Got lineage id %s from local since failed to get git info.", lineage_id) # hash the value to avoid it gets too long, and it's not user visible. lineage_id = hashlib.sha256(lineage_id.encode()).hexdigest() return lineage_id
Get the lineage id for flow. The flow lineage id will be same for same flow in same GIT repo or device. If the flow locates in GIT repo: use Repo name + relative path to flow_dir as session id Otherwise: use device id + absolute path to flow_dir as session id :param flow_dir: flow directory
3,978
import hashlib import os from os import PathLike from pathlib import Path from typing import Union from promptflow._sdk._constants import DAG_FILE_NAME, DEFAULT_ENCODING from promptflow._utils.logger_utils import LoggerFactory from promptflow._utils.yaml_utils import dump_yaml, load_yaml def resolve_flow_path(flow_path: Path): """Resolve given flow path to dag file path.""" if flow_path.is_dir(): flow_path = flow_path / DAG_FILE_NAME return flow_path The provided code snippet includes necessary dependencies for implementing the `load_flow_dag` function. Write a Python function `def load_flow_dag(flow_path: Path)` to solve the following problem: Load flow dag from given flow path. Here is the function: def load_flow_dag(flow_path: Path): """Load flow dag from given flow path.""" flow_path = resolve_flow_path(flow_path) if not flow_path.exists(): raise FileNotFoundError(f"Flow file {flow_path} not found") with open(flow_path, "r", encoding=DEFAULT_ENCODING) as f: flow_dag = load_yaml(f) return flow_path, flow_dag
Load flow dag from given flow path.
3,979
import hashlib import os from os import PathLike from pathlib import Path from typing import Union from promptflow._sdk._constants import DAG_FILE_NAME, DEFAULT_ENCODING from promptflow._utils.logger_utils import LoggerFactory from promptflow._utils.yaml_utils import dump_yaml, load_yaml def resolve_flow_path(flow_path: Path): """Resolve given flow path to dag file path.""" if flow_path.is_dir(): flow_path = flow_path / DAG_FILE_NAME return flow_path The provided code snippet includes necessary dependencies for implementing the `dump_flow_dag` function. Write a Python function `def dump_flow_dag(flow_dag: dict, flow_path: Path)` to solve the following problem: Dump flow dag to given flow path. Here is the function: def dump_flow_dag(flow_dag: dict, flow_path: Path): """Dump flow dag to given flow path.""" flow_path = resolve_flow_path(flow_path) with open(flow_path, "w", encoding=DEFAULT_ENCODING) as f: dump_yaml(flow_dag, f) return flow_path
Dump flow dag to given flow path.
3,980
import contextlib import contextvars import functools import importlib import json import logging import os import re import shutil import time import traceback from datetime import datetime from pathlib import Path from typing import Any, Dict, Iterable, Iterator, List, Optional, TypeVar, Union from promptflow._constants import DEFAULT_ENCODING from promptflow.contracts.multimedia import PFBytes from promptflow.contracts.types import AssistantDefinition def camel_to_snake(text: str) -> Optional[str]: text = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", text) return re.sub("([a-z0-9])([A-Z])", r"\1_\2", text).lower()
null
3,981
import contextlib import contextvars import functools import importlib import json import logging import os import re import shutil import time import traceback from datetime import datetime from pathlib import Path from typing import Any, Dict, Iterable, Iterator, List, Optional, TypeVar, Union from promptflow._constants import DEFAULT_ENCODING from promptflow.contracts.multimedia import PFBytes from promptflow.contracts.types import AssistantDefinition def is_json_serializable(value: Any) -> bool: try: json.dumps(value) return True except TypeError: return False
null
3,982
import contextlib import contextvars import functools import importlib import json import logging import os import re import shutil import time import traceback from datetime import datetime from pathlib import Path from typing import Any, Dict, Iterable, Iterator, List, Optional, TypeVar, Union from promptflow._constants import DEFAULT_ENCODING from promptflow.contracts.multimedia import PFBytes from promptflow.contracts.types import AssistantDefinition def load_json(file_path: Union[str, Path]) -> dict: if os.path.getsize(file_path) > 0: with open(file_path, "r") as f: return json.load(f) return {}
null
3,983
import contextlib import contextvars import functools import importlib import json import logging import os import re import shutil import time import traceback from datetime import datetime from pathlib import Path from typing import Any, Dict, Iterable, Iterator, List, Optional, TypeVar, Union from promptflow._constants import DEFAULT_ENCODING from promptflow.contracts.multimedia import PFBytes from promptflow.contracts.types import AssistantDefinition def dump_list_to_jsonl(file_path: Union[str, Path], list_data: List[Dict]): with open(file_path, "w", encoding=DEFAULT_ENCODING) as jsonl_file: for data in list_data: json.dump(data, jsonl_file, ensure_ascii=False) jsonl_file.write("\n")
null
3,984
import contextlib import contextvars import functools import importlib import json import logging import os import re import shutil import time import traceback from datetime import datetime from pathlib import Path from typing import Any, Dict, Iterable, Iterator, List, Optional, TypeVar, Union from promptflow._constants import DEFAULT_ENCODING from promptflow.contracts.multimedia import PFBytes from promptflow.contracts.types import AssistantDefinition def load_list_from_jsonl(file: Union[str, Path]): content = [] with open(file, "r", encoding=DEFAULT_ENCODING) as fin: for line in fin: content.append(json.loads(line)) return content
null
3,985
import contextlib import contextvars import functools import importlib import json import logging import os import re import shutil import time import traceback from datetime import datetime from pathlib import Path from typing import Any, Dict, Iterable, Iterator, List, Optional, TypeVar, Union from promptflow._constants import DEFAULT_ENCODING from promptflow.contracts.multimedia import PFBytes from promptflow.contracts.types import AssistantDefinition def transpose(values: List[Dict[str, Any]], keys: Optional[List] = None) -> Dict[str, List]: keys = keys or list(values[0].keys()) return {key: [v.get(key) for v in values] for key in keys}
null
3,986
import contextlib import contextvars import functools import importlib import json import logging import os import re import shutil import time import traceback from datetime import datetime from pathlib import Path from typing import Any, Dict, Iterable, Iterator, List, Optional, TypeVar, Union from promptflow._constants import DEFAULT_ENCODING from promptflow.contracts.multimedia import PFBytes from promptflow.contracts.types import AssistantDefinition def reverse_transpose(values: Dict[str, List]) -> List[Dict[str, Any]]: # Setup a result list same len with values value_lists = list(values.values()) _len = len(value_lists[0]) if any(len(value_list) != _len for value_list in value_lists): raise Exception(f"Value list of each key must have same length, please check {values!r}.") result = [] for i in range(_len): result.append({}) for key, vals in values.items(): for _idx, val in enumerate(vals): result[_idx][key] = val return result
null
3,987
import contextlib import contextvars import functools import importlib import json import logging import os import re import shutil import time import traceback from datetime import datetime from pathlib import Path from typing import Any, Dict, Iterable, Iterator, List, Optional, TypeVar, Union from promptflow._constants import DEFAULT_ENCODING from promptflow.contracts.multimedia import PFBytes from promptflow.contracts.types import AssistantDefinition def deprecated(f=None, replace=None, version=None): if f is None: return functools.partial(deprecated, replace=replace, version=version) msg = [f"Function {f.__qualname__!r} is deprecated."] if version: msg.append(f"Deprecated since version {version}.") if replace: msg.append(f"Use {replace!r} instead.") msg = " ".join(msg) @functools.wraps(f) def wrapper(*args, **kwargs): logging.warning(msg) return f(*args, **kwargs) return wrapper
null
3,988
import contextlib import contextvars import functools import importlib import json import logging import os import re import shutil import time import traceback from datetime import datetime from pathlib import Path from typing import Any, Dict, Iterable, Iterator, List, Optional, TypeVar, Union from promptflow._constants import DEFAULT_ENCODING from promptflow.contracts.multimedia import PFBytes from promptflow.contracts.types import AssistantDefinition def try_import(module, error_message, raise_error=True): try: importlib.import_module(module) except ImportError as e: ex_message = f"{error_message} Root cause: {e!r}" logging.warning(ex_message) if raise_error: raise Exception(ex_message)
null
3,989
import contextlib import contextvars import functools import importlib import json import logging import os import re import shutil import time import traceback from datetime import datetime from pathlib import Path from typing import Any, Dict, Iterable, Iterator, List, Optional, TypeVar, Union from promptflow._constants import DEFAULT_ENCODING from promptflow.contracts.multimedia import PFBytes from promptflow.contracts.types import AssistantDefinition def is_in_ci_pipeline(): if os.environ.get("IS_IN_CI_PIPELINE") == "true": return True return False
null
3,990
import contextlib import contextvars import functools import importlib import json import logging import os import re import shutil import time import traceback from datetime import datetime from pathlib import Path from typing import Any, Dict, Iterable, Iterator, List, Optional, TypeVar, Union from promptflow._constants import DEFAULT_ENCODING from promptflow.contracts.multimedia import PFBytes from promptflow.contracts.types import AssistantDefinition T = TypeVar("T") def count_and_log_progress( inputs: Iterable[T], logger: logging.Logger, total_count: int, formatter="{count} / {total_count} finished." ) -> Iterator[T]: log_interval = max(int(total_count / 10), 1) count = 0 for item in inputs: count += 1 if count % log_interval == 0 or count == total_count: logger.info(formatter.format(count=count, total_count=total_count)) yield item
null
3,991
import contextlib import contextvars import functools import importlib import json import logging import os import re import shutil import time import traceback from datetime import datetime from pathlib import Path from typing import Any, Dict, Iterable, Iterator, List, Optional, TypeVar, Union from promptflow._constants import DEFAULT_ENCODING from promptflow.contracts.multimedia import PFBytes from promptflow.contracts.types import AssistantDefinition def log_progress( run_start_time: datetime, logger: logging.Logger, count: int, total_count: int, formatter="Finished {count} / {total_count} lines.", *, last_log_count: Optional[int] = None, ): # Calculate log_interval to determine when to log progress. # If total_count is less than 100, log every 10% of total_count; otherwise, log every 10 lines. log_interval = min(10, max(int(total_count / 10), 1)) # If last_log_count is not None, determine whether to log based on whether the difference # between the current count and the previous count exceeds log_interval. # Otherwise, decide based on whether the current count is evenly divisible by log_interval. if last_log_count: log_flag = (count - last_log_count) >= log_interval else: log_flag = count % log_interval == 0 if count > 0 and (log_flag or count == total_count): average_execution_time = round((datetime.utcnow().timestamp() - run_start_time.timestamp()) / count, 2) estimated_execution_time = round(average_execution_time * (total_count - count), 2) logger.info(formatter.format(count=count, total_count=total_count)) logger.info( f"Average execution time for completed lines: {average_execution_time} seconds. " f"Estimated time for incomplete lines: {estimated_execution_time} seconds." )
null
3,992
import contextlib import contextvars import functools import importlib import json import logging import os import re import shutil import time import traceback from datetime import datetime from pathlib import Path from typing import Any, Dict, Iterable, Iterator, List, Optional, TypeVar, Union from promptflow._constants import DEFAULT_ENCODING from promptflow.contracts.multimedia import PFBytes from promptflow.contracts.types import AssistantDefinition def format_user_stacktrace(frame): # TODO: Maybe we can filter all frames from our code base to make it clean? frame_summaries = traceback.extract_stack(frame) user_frame_summaries = extract_user_frame_summaries(frame_summaries) return traceback.format_list(user_frame_summaries) def generate_elapsed_time_messages(func_name: str, start_time: float, interval: int, thread_id: int): import sys frames = sys._current_frames() if thread_id not in frames: thread_msg = ( f"thread {thread_id} cannot be found in sys._current_frames, " + "maybe it has been terminated due to unexpected errors." ) else: frame = frames[thread_id] stack_msgs = format_user_stacktrace(frame) stack_msg = "".join(stack_msgs) thread_msg = f"stacktrace of thread {thread_id}:\n{stack_msg}" elapse_time = time.perf_counter() - start_time # Make elapse time a multiple of interval. elapse_time = round(elapse_time / interval) * interval msgs = [f"{func_name} has been running for {elapse_time:.0f} seconds, {thread_msg}"] return msgs
null
3,993
import contextlib import contextvars import functools import importlib import json import logging import os import re import shutil import time import traceback from datetime import datetime from pathlib import Path from typing import Any, Dict, Iterable, Iterator, List, Optional, TypeVar, Union from promptflow._constants import DEFAULT_ENCODING from promptflow.contracts.multimedia import PFBytes from promptflow.contracts.types import AssistantDefinition def set_context(context: contextvars.Context): for var, value in context.items(): var.set(value)
null
3,994
import contextlib import contextvars import functools import importlib import json import logging import os import re import shutil import time import traceback from datetime import datetime from pathlib import Path from typing import Any, Dict, Iterable, Iterator, List, Optional, TypeVar, Union from promptflow._constants import DEFAULT_ENCODING from promptflow.contracts.multimedia import PFBytes from promptflow.contracts.types import AssistantDefinition The provided code snippet includes necessary dependencies for implementing the `convert_inputs_mapping_to_param` function. Write a Python function `def convert_inputs_mapping_to_param(inputs_mapping: dict)` to solve the following problem: Use this function to convert inputs_mapping to a string that can be passed to component as a string parameter, we have to do this since we can't pass a dict as a parameter to component. # TODO: Finalize the format of inputs_mapping Here is the function: def convert_inputs_mapping_to_param(inputs_mapping: dict): """Use this function to convert inputs_mapping to a string that can be passed to component as a string parameter, we have to do this since we can't pass a dict as a parameter to component. # TODO: Finalize the format of inputs_mapping """ return ",".join([f"{k}={v}" for k, v in inputs_mapping.items()])
Use this function to convert inputs_mapping to a string that can be passed to component as a string parameter, we have to do this since we can't pass a dict as a parameter to component. # TODO: Finalize the format of inputs_mapping
3,995
import contextlib import contextvars import functools import importlib import json import logging import os import re import shutil import time import traceback from datetime import datetime from pathlib import Path from typing import Any, Dict, Iterable, Iterator, List, Optional, TypeVar, Union from promptflow._constants import DEFAULT_ENCODING from promptflow.contracts.multimedia import PFBytes from promptflow.contracts.types import AssistantDefinition def environment_variable_overwrite(key, val): if key in os.environ.keys(): backup_value = os.environ[key] else: backup_value = None os.environ[key] = val try: yield finally: if backup_value: os.environ[key] = backup_value else: os.environ.pop(key)
null
3,996
import contextlib import contextvars import functools import importlib import json import logging import os import re import shutil import time import traceback from datetime import datetime from pathlib import Path from typing import Any, Dict, Iterable, Iterator, List, Optional, TypeVar, Union from promptflow._constants import DEFAULT_ENCODING from promptflow.contracts.multimedia import PFBytes from promptflow.contracts.types import AssistantDefinition The provided code snippet includes necessary dependencies for implementing the `resolve_dir_to_absolute` function. Write a Python function `def resolve_dir_to_absolute(base_dir: Union[str, Path], sub_dir: Union[str, Path]) -> Path` to solve the following problem: Resolve directory to absolute path with base_dir as root Here is the function: def resolve_dir_to_absolute(base_dir: Union[str, Path], sub_dir: Union[str, Path]) -> Path: """Resolve directory to absolute path with base_dir as root""" path = sub_dir if isinstance(sub_dir, Path) else Path(sub_dir) if not path.is_absolute(): base_dir = base_dir if isinstance(base_dir, Path) else Path(base_dir) path = base_dir / sub_dir return path
Resolve directory to absolute path with base_dir as root
3,997
import contextlib import contextvars import functools import importlib import json import logging import os import re import shutil import time import traceback from datetime import datetime from pathlib import Path from typing import Any, Dict, Iterable, Iterator, List, Optional, TypeVar, Union from promptflow._constants import DEFAULT_ENCODING from promptflow.contracts.multimedia import PFBytes from promptflow.contracts.types import AssistantDefinition The provided code snippet includes necessary dependencies for implementing the `parse_ua_to_dict` function. Write a Python function `def parse_ua_to_dict(ua)` to solve the following problem: Parse string user agent to dict with name as ua name and value as ua version. Here is the function: def parse_ua_to_dict(ua): """Parse string user agent to dict with name as ua name and value as ua version.""" ua_dict = {} ua_list = ua.split(" ") for item in ua_list: if item: key, value = item.split("/") ua_dict[key] = value return ua_dict
Parse string user agent to dict with name as ua name and value as ua version.
3,998
import contextlib import contextvars import functools import importlib import json import logging import os import re import shutil import time import traceback from datetime import datetime from pathlib import Path from typing import Any, Dict, Iterable, Iterator, List, Optional, TypeVar, Union from promptflow._constants import DEFAULT_ENCODING from promptflow.contracts.multimedia import PFBytes from promptflow.contracts.types import AssistantDefinition The provided code snippet includes necessary dependencies for implementing the `get_int_env_var` function. Write a Python function `def get_int_env_var(env_var_name, default_value=None)` to solve the following problem: The function `get_int_env_var` retrieves an integer environment variable value, with an optional default value if the variable is not set or cannot be converted to an integer. :param env_var_name: The name of the environment variable you want to retrieve the value of :param default_value: The default value is the value that will be returned if the environment variable is not found or if it cannot be converted to an integer :return: an integer value. Here is the function: def get_int_env_var(env_var_name, default_value=None): """ The function `get_int_env_var` retrieves an integer environment variable value, with an optional default value if the variable is not set or cannot be converted to an integer. :param env_var_name: The name of the environment variable you want to retrieve the value of :param default_value: The default value is the value that will be returned if the environment variable is not found or if it cannot be converted to an integer :return: an integer value. """ try: return int(os.environ.get(env_var_name, default_value)) except Exception: return default_value
The function `get_int_env_var` retrieves an integer environment variable value, with an optional default value if the variable is not set or cannot be converted to an integer. :param env_var_name: The name of the environment variable you want to retrieve the value of :param default_value: The default value is the value that will be returned if the environment variable is not found or if it cannot be converted to an integer :return: an integer value.
3,999
import contextlib import contextvars import functools import importlib import json import logging import os import re import shutil import time import traceback from datetime import datetime from pathlib import Path from typing import Any, Dict, Iterable, Iterator, List, Optional, TypeVar, Union from promptflow._constants import DEFAULT_ENCODING from promptflow.contracts.multimedia import PFBytes from promptflow.contracts.types import AssistantDefinition def prompt_input(msg): return input("\n===> " + msg) def prompt_y_n(msg, default=None): if default not in [None, "y", "n"]: raise ValueError("Valid values for default are 'y', 'n' or None") y = "Y" if default == "y" else "y" n = "N" if default == "n" else "n" while True: ans = prompt_input("{} ({}/{}): ".format(msg, y, n)) if ans.lower() == n.lower(): return False if ans.lower() == y.lower(): return True if default and not ans: return default == y.lower()
null
4,000
import contextlib import contextvars import functools import importlib import json import logging import os import re import shutil import time import traceback from datetime import datetime from pathlib import Path from typing import Any, Dict, Iterable, Iterator, List, Optional, TypeVar, Union from promptflow._constants import DEFAULT_ENCODING from promptflow.contracts.multimedia import PFBytes from promptflow.contracts.types import AssistantDefinition def _normalize_identifier_name(name): normalized_name = name.lower() normalized_name = re.sub(r"[\W_]", " ", normalized_name) # No non-word characters normalized_name = re.sub(" +", " ", normalized_name).strip() # No double spaces, leading or trailing spaces if re.match(r"\d", normalized_name): normalized_name = "n" + normalized_name # No leading digits return normalized_name def _sanitize_python_variable_name(name: str): return _normalize_identifier_name(name).replace(" ", "_")
null
4,001
import contextlib import contextvars import functools import importlib import json import logging import os import re import shutil import time import traceback from datetime import datetime from pathlib import Path from typing import Any, Dict, Iterable, Iterator, List, Optional, TypeVar, Union from promptflow._constants import DEFAULT_ENCODING from promptflow.contracts.multimedia import PFBytes from promptflow.contracts.types import AssistantDefinition def _match_reference(env_val: str): env_val = env_val.strip() m = re.match(r"^\$\{([^.]+)\.([^.]+)}$", env_val) if not m: return None, None name, key = m.groups() return name, key
null
4,002
import contextlib import contextvars import functools import importlib import json import logging import os import re import shutil import time import traceback from datetime import datetime from pathlib import Path from typing import Any, Dict, Iterable, Iterator, List, Optional, TypeVar, Union from promptflow._constants import DEFAULT_ENCODING from promptflow.contracts.multimedia import PFBytes from promptflow.contracts.types import AssistantDefinition The provided code snippet includes necessary dependencies for implementing the `copy_file_except` function. Write a Python function `def copy_file_except(src_dir, dst_dir, exclude_file)` to solve the following problem: Copy all files from src_dir to dst_dir recursively, excluding a specific file directly under the root of src_dir. :param src_dir: Source directory path :type src_dir: str :param dst_dir: Destination directory path :type dst_dir: str :param exclude_file: Name of the file to exclude from copying :type exclude_file: str Here is the function: def copy_file_except(src_dir, dst_dir, exclude_file): """ Copy all files from src_dir to dst_dir recursively, excluding a specific file directly under the root of src_dir. :param src_dir: Source directory path :type src_dir: str :param dst_dir: Destination directory path :type dst_dir: str :param exclude_file: Name of the file to exclude from copying :type exclude_file: str """ os.makedirs(dst_dir, exist_ok=True) for root, dirs, files in os.walk(src_dir): rel_path = os.path.relpath(root, src_dir) current_dst_dir = os.path.join(dst_dir, rel_path) os.makedirs(current_dst_dir, exist_ok=True) for file in files: if rel_path == "." and file == exclude_file: continue # Skip the excluded file src_file_path = os.path.join(root, file) dst_file_path = os.path.join(current_dst_dir, file) shutil.copy2(src_file_path, dst_file_path)
Copy all files from src_dir to dst_dir recursively, excluding a specific file directly under the root of src_dir. :param src_dir: Source directory path :type src_dir: str :param dst_dir: Destination directory path :type dst_dir: str :param exclude_file: Name of the file to exclude from copying :type exclude_file: str
4,003
import contextlib import contextvars import functools import importlib import json import logging import os import re import shutil import time import traceback from datetime import datetime from pathlib import Path from typing import Any, Dict, Iterable, Iterator, List, Optional, TypeVar, Union from promptflow._constants import DEFAULT_ENCODING from promptflow.contracts.multimedia import PFBytes from promptflow.contracts.types import AssistantDefinition The provided code snippet includes necessary dependencies for implementing the `in_jupyter_notebook` function. Write a Python function `def in_jupyter_notebook() -> bool` to solve the following problem: Checks if user is using a Jupyter Notebook. This is necessary because logging is not allowed in non-Jupyter contexts. Adapted from https://stackoverflow.com/a/22424821 Here is the function: def in_jupyter_notebook() -> bool: """ Checks if user is using a Jupyter Notebook. This is necessary because logging is not allowed in non-Jupyter contexts. Adapted from https://stackoverflow.com/a/22424821 """ try: # cspell:ignore ipython from IPython import get_ipython if "IPKernelApp" not in get_ipython().config: return False except ImportError: return False except AttributeError: return False return True
Checks if user is using a Jupyter Notebook. This is necessary because logging is not allowed in non-Jupyter contexts. Adapted from https://stackoverflow.com/a/22424821
4,004
import contextlib import contextvars import functools import importlib import json import logging import os import re import shutil import time import traceback from datetime import datetime from pathlib import Path from typing import Any, Dict, Iterable, Iterator, List, Optional, TypeVar, Union from promptflow._constants import DEFAULT_ENCODING from promptflow.contracts.multimedia import PFBytes from promptflow.contracts.types import AssistantDefinition def snake_to_camel(name): return re.sub(r"(?:^|_)([a-z])", lambda x: x.group(1).upper(), name)
null
4,005
import contextlib import contextvars import functools import importlib import json import logging import os import re import shutil import time import traceback from datetime import datetime from pathlib import Path from typing import Any, Dict, Iterable, Iterator, List, Optional, TypeVar, Union from promptflow._constants import DEFAULT_ENCODING from promptflow.contracts.multimedia import PFBytes from promptflow.contracts.types import AssistantDefinition The provided code snippet includes necessary dependencies for implementing the `prepare_folder` function. Write a Python function `def prepare_folder(path: Union[str, Path]) -> Path` to solve the following problem: Create folder if not exists and return the folder path. Here is the function: def prepare_folder(path: Union[str, Path]) -> Path: """Create folder if not exists and return the folder path.""" path = Path(path) path.mkdir(parents=True, exist_ok=True) return path
Create folder if not exists and return the folder path.
4,006
import time from functools import wraps from typing import Tuple, Type, Union from requests import Response from promptflow._utils.logger_utils import LoggerFactory logger = LoggerFactory.get_logger(__name__) The provided code snippet includes necessary dependencies for implementing the `retry` function. Write a Python function `def retry(exception_to_check: Union[Type[Exception], Tuple[Type[Exception], ...]], tries=4, delay=3, backoff=2)` to solve the following problem: From https://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/ Retry calling the decorated function using an exponential backoff. http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/ original from: http://wiki.python.org/moin/PythonDecoratorLibrary#Retry :param exception_to_check: the exception to check. may be a tuple of exceptions to check :type exception_to_check: Exception or tuple :param tries: number of times to try (not retry) before giving up :type tries: int :param delay: initial delay between retries in seconds :type delay: int :param backoff: backoff multiplier e.g. value of 2 will double the delay each retry :type backoff: int :param logger: log the retry action if specified :type logger: logging.Logger Here is the function: def retry(exception_to_check: Union[Type[Exception], Tuple[Type[Exception], ...]], tries=4, delay=3, backoff=2): """ From https://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/ Retry calling the decorated function using an exponential backoff. http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/ original from: http://wiki.python.org/moin/PythonDecoratorLibrary#Retry :param exception_to_check: the exception to check. may be a tuple of exceptions to check :type exception_to_check: Exception or tuple :param tries: number of times to try (not retry) before giving up :type tries: int :param delay: initial delay between retries in seconds :type delay: int :param backoff: backoff multiplier e.g. value of 2 will double the delay each retry :type backoff: int :param logger: log the retry action if specified :type logger: logging.Logger """ def deco_retry(f): @wraps(f) def f_retry(*args, **kwargs): retry_times, delay_seconds = tries, delay while retry_times > 1: try: logger.debug("Running %s, %d more tries to go.", str(f), retry_times) return f(*args, **kwargs) except exception_to_check: time.sleep(delay_seconds) retry_times -= 1 delay_seconds *= backoff logger.warning("%s, Retrying in %d seconds...", str(exception_to_check), delay_seconds) return f(*args, **kwargs) return f_retry # true decorator return deco_retry
From https://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/ Retry calling the decorated function using an exponential backoff. http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/ original from: http://wiki.python.org/moin/PythonDecoratorLibrary#Retry :param exception_to_check: the exception to check. may be a tuple of exceptions to check :type exception_to_check: Exception or tuple :param tries: number of times to try (not retry) before giving up :type tries: int :param delay: initial delay between retries in seconds :type delay: int :param backoff: backoff multiplier e.g. value of 2 will double the delay each retry :type backoff: int :param logger: log the retry action if specified :type logger: logging.Logger
4,007
import time from functools import wraps from typing import Tuple, Type, Union from requests import Response from promptflow._utils.logger_utils import LoggerFactory logger = LoggerFactory.get_logger(__name__) HTTP_RETRY_CODES = set(range(999)) - HTTP_SAFE_CODES The provided code snippet includes necessary dependencies for implementing the `http_retry_wrapper` function. Write a Python function `def http_retry_wrapper(f, tries=4, delay=3, backoff=2)` to solve the following problem: :param f: function to be retried, should return a Response object. :type f: Callable :param tries: number of times to try (not retry) before giving up :type tries: int :param delay: initial delay between retries in seconds :type delay: int :param backoff: backoff multiplier e.g. value of 2 will double the delay each retry :type backoff: int Here is the function: def http_retry_wrapper(f, tries=4, delay=3, backoff=2): """ :param f: function to be retried, should return a Response object. :type f: Callable :param tries: number of times to try (not retry) before giving up :type tries: int :param delay: initial delay between retries in seconds :type delay: int :param backoff: backoff multiplier e.g. value of 2 will double the delay each retry :type backoff: int """ @wraps(f) def f_retry(*args, **kwargs): retry_times, delay_seconds = tries, delay while retry_times > 1: result = f(*args, **kwargs) if not isinstance(result, Response): logger.debug(f"Not a retryable function, expected return type {Response}, got {type(result)}.") return result if result.status_code not in HTTP_RETRY_CODES: return result logger.warning( f"Retryable error code {result.status_code} returned, retrying in {delay_seconds} seconds. " f"Function {f.__name__}, Reason: {result.reason}" ) time.sleep(delay_seconds) retry_times -= 1 delay_seconds *= backoff return f(*args, **kwargs) return f_retry
:param f: function to be retried, should return a Response object. :type f: Callable :param tries: number of times to try (not retry) before giving up :type tries: int :param delay: initial delay between retries in seconds :type delay: int :param backoff: backoff multiplier e.g. value of 2 will double the delay each retry :type backoff: int
4,008
import logging import os import signal import psutil from promptflow._utils.logger_utils import bulk_logger The provided code snippet includes necessary dependencies for implementing the `block_terminate_signal_to_parent` function. Write a Python function `def block_terminate_signal_to_parent()` to solve the following problem: In uvicorn app, the main process listens for requests and handles graceful shutdowns through signal listeners set up at initialization. These listeners use a file descriptor for event notifications. However, when a child process is forked within the application, it inherits this file descriptor, leading to an issue where signals sent to terminate the child process are also intercepted by the main process, causing an unintended shutdown of the entire application. To avoid this, we should return the default behavior of signal handlers for child process and call signal.set_wakeup_fd(-1) in the child process to prevent it from using the parent's file descriptor and avoiding unintended shutdowns of the main process. References: https://github.com/tiangolo/fastapi/discussions/7442 Here is the function: def block_terminate_signal_to_parent(): """ In uvicorn app, the main process listens for requests and handles graceful shutdowns through signal listeners set up at initialization. These listeners use a file descriptor for event notifications. However, when a child process is forked within the application, it inherits this file descriptor, leading to an issue where signals sent to terminate the child process are also intercepted by the main process, causing an unintended shutdown of the entire application. To avoid this, we should return the default behavior of signal handlers for child process and call signal.set_wakeup_fd(-1) in the child process to prevent it from using the parent's file descriptor and avoiding unintended shutdowns of the main process. References: https://github.com/tiangolo/fastapi/discussions/7442 """ signal.set_wakeup_fd(-1) signal.signal(signal.SIGTERM, signal.SIG_DFL) signal.signal(signal.SIGINT, signal.SIG_DFL)
In uvicorn app, the main process listens for requests and handles graceful shutdowns through signal listeners set up at initialization. These listeners use a file descriptor for event notifications. However, when a child process is forked within the application, it inherits this file descriptor, leading to an issue where signals sent to terminate the child process are also intercepted by the main process, causing an unintended shutdown of the entire application. To avoid this, we should return the default behavior of signal handlers for child process and call signal.set_wakeup_fd(-1) in the child process to prevent it from using the parent's file descriptor and avoiding unintended shutdowns of the main process. References: https://github.com/tiangolo/fastapi/discussions/7442
4,009
import logging import os import signal import psutil from promptflow._utils.logger_utils import bulk_logger The provided code snippet includes necessary dependencies for implementing the `get_available_max_worker_count` function. Write a Python function `def get_available_max_worker_count(logger: logging.Logger = bulk_logger)` to solve the following problem: When creating processes using the spawn method, it consumes certain resources. So we can use this method to determine how many workers can be maximally created. Here is the function: def get_available_max_worker_count(logger: logging.Logger = bulk_logger): """ When creating processes using the spawn method, it consumes certain resources. So we can use this method to determine how many workers can be maximally created. """ pid = os.getpid() mem_info = psutil.virtual_memory() available_memory = mem_info.available / (1024 * 1024) # in MB process = psutil.Process(pid) process_memory_info = process.memory_info() process_memory = process_memory_info.rss / (1024 * 1024) # in MB estimated_available_worker_count = int(available_memory // process_memory) if estimated_available_worker_count < 1: # TODO: For the case of vector db, Optimize execution logic # 1. Let the main process not consume memory because it does not actually invoke # 2. When the degree of parallelism is 1, main process executes the task directly # and not create the child process logger.warning( f"Current system's available memory is {available_memory}MB, less than the memory " f"{process_memory}MB required by the process. The maximum available worker count is 1." ) estimated_available_worker_count = 1 else: logger.info( f"Current system's available memory is {available_memory}MB, " f"memory consumption of current process is {process_memory}MB, " f"estimated available worker count is {available_memory}/{process_memory} " f"= {estimated_available_worker_count}" ) return estimated_available_worker_count
When creating processes using the spawn method, it consumes certain resources. So we can use this method to determine how many workers can be maximally created.
4,010
import logging import os from pathlib import Path from typing import Any, Dict, List, Tuple, Union from promptflow.exceptions import ErrorTarget, UserErrorException def load_df(local_path: Union[str, Path], logger: logging.Logger = None, max_rows_count: int = None) -> "DataFrame": """load data from local file to df. For the usage of PRS.""" lp = local_path if isinstance(local_path, Path) else Path(local_path) try: if lp.is_file(): df = _pd_read_file(local_path, logger=logger, max_rows_count=max_rows_count) # honor max_rows_count if it is specified if max_rows_count and len(df) > max_rows_count: df = df.head(max_rows_count) else: df = _handle_dir(local_path, max_rows_count=max_rows_count, logger=logger) except ValueError as e: raise InvalidUserData( message_format="Fail to load invalid data. We support file formats: csv, tsv, json, jsonl, parquet. " "Please check input data." ) from e return df The provided code snippet includes necessary dependencies for implementing the `load_data` function. Write a Python function `def load_data( local_path: Union[str, Path], *, logger: logging.Logger = None, max_rows_count: int = None ) -> List[Dict[str, Any]]` to solve the following problem: load data from local file Here is the function: def load_data( local_path: Union[str, Path], *, logger: logging.Logger = None, max_rows_count: int = None ) -> List[Dict[str, Any]]: """load data from local file""" df = load_df(local_path, logger, max_rows_count=max_rows_count) # convert dataframe to list of dict result = [] for _, row in df.iterrows(): result.append(row.to_dict()) return result
load data from local file
4,011
from dataclasses import fields, is_dataclass from datetime import datetime from enum import Enum from typing import Any, Callable, Dict, List, Type, TypeVar from promptflow._constants import DEFAULT_OUTPUT_NAME from promptflow._core.generator_proxy import GeneratorProxy from promptflow.contracts.tool import ConnectionType def serialize(value: object, remove_null: bool = False, serialization_funcs: Dict[type, Callable] = None) -> dict: if serialization_funcs: for cls, f in serialization_funcs.items(): if isinstance(value, cls): return f(value) if isinstance(value, datetime): return value.isoformat() + "Z" if isinstance(value, Enum): return value.value if isinstance(value, list): return [serialize(v, remove_null, serialization_funcs) for v in value] if isinstance(value, GeneratorProxy): # TODO: The current implementation of the serialize function is not self-explanatory, as value.items is mutable # whereas the serialize function should deal with a fixed object. We should rename the function to # to_serializable to better reflect its purpose. return value.items # Note that custom connection check should before dict check if ConnectionType.is_connection_value(value): return ConnectionType.serialize_conn(value) if isinstance(value, dict): return {k: serialize(v, remove_null, serialization_funcs) for k, v in value.items()} if is_dataclass(value): if hasattr(value, "serialize"): result = value.serialize() else: result = { f.name: serialize(getattr(value, f.name), remove_null, serialization_funcs) for f in fields(value) } if not remove_null: return result null_keys = [k for k, v in result.items() if v is None] for k in null_keys: result.pop(k) return result try: from pydantic import BaseModel if isinstance(value, BaseModel): # Handle pydantic model, which is used in langchain return value.dict() except ImportError: # Ignore ImportError if pydantic is not installed pass return value
null
4,012
from dataclasses import fields, is_dataclass from datetime import datetime from enum import Enum from typing import Any, Callable, Dict, List, Type, TypeVar from promptflow._constants import DEFAULT_OUTPUT_NAME from promptflow._core.generator_proxy import GeneratorProxy from promptflow.contracts.tool import ConnectionType def assertEqual(a: dict, b: dict, path: str = ""): if isinstance(a, dict): assert isinstance(b, dict), f"{path}: {type(a)} != {type(b)}" assert set(a.keys()) == set(b.keys()), f"{path}: {set(a.keys())} != {set(b.keys())}" for key in a.keys(): assertEqual(a[key], b[key], path + "." + key) elif isinstance(a, list): assert isinstance(b, list), f"{path}: {type(a)} != {type(b)}" assert len(a) == len(b), f"{path}: {len(a)} != {len(b)}" for i in range(len(a)): assertEqual(a[i], b[i], path + f"[{i}]") else: assert a == b, f"{path}: {a} != {b}"
null
4,013
from dataclasses import fields, is_dataclass from datetime import datetime from enum import Enum from typing import Any, Callable, Dict, List, Type, TypeVar from promptflow._constants import DEFAULT_OUTPUT_NAME from promptflow._core.generator_proxy import GeneratorProxy from promptflow.contracts.tool import ConnectionType The provided code snippet includes necessary dependencies for implementing the `convert_eager_flow_output_to_dict` function. Write a Python function `def convert_eager_flow_output_to_dict(value: Any)` to solve the following problem: Convert the output of eager flow to a dict. Since the output of eager flow may not be a dict, we need to convert it to a dict in batch mode. Examples: 1. If the output is a dict, return it directly: value = {"output": 1} -> {"output": 1} 2. If the output is a dataclass, convert it to a dict: value = SampleDataClass(output=1) -> {"output": 1} 3. If the output is not a dict or dataclass, convert it to a dict by adding a key "output": value = 1 -> {"output": 1} Here is the function: def convert_eager_flow_output_to_dict(value: Any): """ Convert the output of eager flow to a dict. Since the output of eager flow may not be a dict, we need to convert it to a dict in batch mode. Examples: 1. If the output is a dict, return it directly: value = {"output": 1} -> {"output": 1} 2. If the output is a dataclass, convert it to a dict: value = SampleDataClass(output=1) -> {"output": 1} 3. If the output is not a dict or dataclass, convert it to a dict by adding a key "output": value = 1 -> {"output": 1} """ if isinstance(value, dict): return value elif is_dataclass(value): return {f.name: getattr(value, f.name) for f in fields(value)} else: return {DEFAULT_OUTPUT_NAME: value}
Convert the output of eager flow to a dict. Since the output of eager flow may not be a dict, we need to convert it to a dict in batch mode. Examples: 1. If the output is a dict, return it directly: value = {"output": 1} -> {"output": 1} 2. If the output is a dataclass, convert it to a dict: value = SampleDataClass(output=1) -> {"output": 1} 3. If the output is not a dict or dataclass, convert it to a dict by adding a key "output": value = 1 -> {"output": 1}
4,014
import datetime import json import logging from promptflow._constants import ( CLI_PACKAGE_NAME, CURRENT_VERSION, GET_PYPI_INTERVAL_DAY, HINT_INTERVAL_DAY, LAST_CHECK_TIME, LAST_HINT_TIME, LATEST_VERSION, PF_VERSION_CHECK, ) from promptflow._sdk._constants import HOME_PROMPT_FLOW_DIR def get_cached_versions(): from promptflow._sdk._utils import read_write_by_user (HOME_PROMPT_FLOW_DIR / PF_VERSION_CHECK).touch(mode=read_write_by_user(), exist_ok=True) with open(HOME_PROMPT_FLOW_DIR / PF_VERSION_CHECK, "r") as f: try: cached_versions = json.load(f) except json.decoder.JSONDecodeError: cached_versions = {} return cached_versions def dump_cached_versions(cached_versions): with open(HOME_PROMPT_FLOW_DIR / PF_VERSION_CHECK, "w") as f: json.dump(cached_versions, f) def get_latest_version(package_name, installer="PIP"): if installer == "MSI": url = "https://promptflowartifact.blob.core.windows.net/msi-installer/latest_version.json" else: url = f"https://pypi.org/pypi/{package_name}/json" try: import requests response = requests.get(url, timeout=3) if response.status_code == 200: data = response.json() if installer == "MSI": latest_version = data[package_name] else: latest_version = data["info"]["version"] return latest_version else: return None except Exception as ex: # pylint: disable=broad-except logger.debug(f"Failed to get the latest version from '{url}'. {str(ex)}") return None The provided code snippet includes necessary dependencies for implementing the `check_latest_version` function. Write a Python function `def check_latest_version()` to solve the following problem: Get the latest versions from a cached file Here is the function: def check_latest_version(): """Get the latest versions from a cached file""" cached_versions = get_cached_versions() last_check_time = ( datetime.datetime.strptime(cached_versions[LAST_CHECK_TIME], "%Y-%m-%d %H:%M:%S.%f") if LAST_CHECK_TIME in cached_versions else None ) if last_check_time is None or ( datetime.datetime.now() > last_check_time + datetime.timedelta(days=GET_PYPI_INTERVAL_DAY) ): # For hint, we can't know pfazure installed way for now, so we only check the latest version from pypi. version = get_latest_version(CLI_PACKAGE_NAME) if version is not None: cached_versions[LATEST_VERSION] = version cached_versions[LAST_CHECK_TIME] = str(datetime.datetime.now()) dump_cached_versions(cached_versions)
Get the latest versions from a cached file
4,015
import datetime import json import logging from promptflow._constants import ( CLI_PACKAGE_NAME, CURRENT_VERSION, GET_PYPI_INTERVAL_DAY, HINT_INTERVAL_DAY, LAST_CHECK_TIME, LAST_HINT_TIME, LATEST_VERSION, PF_VERSION_CHECK, ) from promptflow._sdk._constants import HOME_PROMPT_FLOW_DIR logger = logging.getLogger(__name__) def get_cached_versions(): from promptflow._sdk._utils import read_write_by_user (HOME_PROMPT_FLOW_DIR / PF_VERSION_CHECK).touch(mode=read_write_by_user(), exist_ok=True) with open(HOME_PROMPT_FLOW_DIR / PF_VERSION_CHECK, "r") as f: try: cached_versions = json.load(f) except json.decoder.JSONDecodeError: cached_versions = {} return cached_versions def dump_cached_versions(cached_versions): with open(HOME_PROMPT_FLOW_DIR / PF_VERSION_CHECK, "w") as f: json.dump(cached_versions, f) The provided code snippet includes necessary dependencies for implementing the `hint_for_update` function. Write a Python function `def hint_for_update()` to solve the following problem: Check if there is a new version of prompt flow available every 7 days. IF yes, log debug info to hint customer to upgrade package. Here is the function: def hint_for_update(): """ Check if there is a new version of prompt flow available every 7 days. IF yes, log debug info to hint customer to upgrade package. """ cached_versions = get_cached_versions() last_hint_time = ( datetime.datetime.strptime(cached_versions[LAST_HINT_TIME], "%Y-%m-%d %H:%M:%S.%f") if LAST_HINT_TIME in cached_versions else None ) if last_hint_time is None or ( datetime.datetime.now() > last_hint_time + datetime.timedelta(days=HINT_INTERVAL_DAY) ): from promptflow._sdk._utils import get_promptflow_sdk_version cached_versions[CURRENT_VERSION] = get_promptflow_sdk_version() if LATEST_VERSION in cached_versions: from packaging.version import parse if parse(cached_versions[CURRENT_VERSION]) < parse(cached_versions[LATEST_VERSION]): cached_versions[LAST_HINT_TIME] = str(datetime.datetime.now()) message = ( f"New prompt flow version available: promptflow-{cached_versions[LATEST_VERSION]}. Running " f"'pf upgrade' to update CLI." ) logger.debug(message) dump_cached_versions(cached_versions)
Check if there is a new version of prompt flow available every 7 days. IF yes, log debug info to hint customer to upgrade package.
4,016
import json import os from datetime import datetime from enum import Enum from traceback import TracebackException, format_tb from types import TracebackType, FrameType from promptflow.exceptions import PromptflowException, SystemErrorException, UserErrorException, ValidationException The provided code snippet includes necessary dependencies for implementing the `get_tb_next` function. Write a Python function `def get_tb_next(tb: TracebackType, next_cnt: int)` to solve the following problem: Return the nth tb_next of input tb. If the tb does not have n tb_next, return the last tb which has a value. n = next_cnt Here is the function: def get_tb_next(tb: TracebackType, next_cnt: int): """Return the nth tb_next of input tb. If the tb does not have n tb_next, return the last tb which has a value. n = next_cnt """ while tb.tb_next and next_cnt > 0: tb = tb.tb_next next_cnt -= 1 return tb
Return the nth tb_next of input tb. If the tb does not have n tb_next, return the last tb which has a value. n = next_cnt
4,017
import json import os from datetime import datetime from enum import Enum from traceback import TracebackException, format_tb from types import TracebackType, FrameType from promptflow.exceptions import PromptflowException, SystemErrorException, UserErrorException, ValidationException The provided code snippet includes necessary dependencies for implementing the `last_frame_info` function. Write a Python function `def last_frame_info(ex: Exception)` to solve the following problem: Return the line number where the error occurred. Here is the function: def last_frame_info(ex: Exception): """Return the line number where the error occurred.""" if ex: tb = TracebackException.from_exception(ex) last_frame = tb.stack[-1] if tb.stack else None if last_frame: return { "filename": last_frame.filename, "lineno": last_frame.lineno, "name": last_frame.name, } return {}
Return the line number where the error occurred.
4,018
import json import os from datetime import datetime from enum import Enum from traceback import TracebackException, format_tb from types import TracebackType, FrameType from promptflow.exceptions import PromptflowException, SystemErrorException, UserErrorException, ValidationException class RootErrorCode: USER_ERROR = "UserError" SYSTEM_ERROR = "SystemError" def infer_error_code_from_class(cls): # Python has a built-in SystemError if cls == SystemErrorException: return RootErrorCode.SYSTEM_ERROR if cls == UserErrorException: return RootErrorCode.USER_ERROR if cls == ValidationException: return "ValidationError" return cls.__name__
null
4,019
import json import os from datetime import datetime from enum import Enum from traceback import TracebackException, format_tb from types import TracebackType, FrameType from promptflow.exceptions import PromptflowException, SystemErrorException, UserErrorException, ValidationException The provided code snippet includes necessary dependencies for implementing the `is_pf_core_frame` function. Write a Python function `def is_pf_core_frame(frame: FrameType)` to solve the following problem: Check if the frame is from promptflow core code. Here is the function: def is_pf_core_frame(frame: FrameType): """Check if the frame is from promptflow core code.""" from promptflow import _core folder_of_core = os.path.dirname(_core.__file__) return folder_of_core in frame.f_code.co_filename
Check if the frame is from promptflow core code.
4,020
import json import os from datetime import datetime from enum import Enum from traceback import TracebackException, format_tb from types import TracebackType, FrameType from promptflow.exceptions import PromptflowException, SystemErrorException, UserErrorException, ValidationException The provided code snippet includes necessary dependencies for implementing the `remove_suffix` function. Write a Python function `def remove_suffix(text: str, suffix: str = None)` to solve the following problem: Given a string, removes specified suffix, if it has. >>> remove_suffix('hello world', 'world') 'hello ' >>> remove_suffix('hello world', 'hello ') 'hello world' >>> remove_suffix('NoColumnFoundError', 'Error') 'NoColumnFound' :param text: string from which prefix will be removed. :param suffix: suffix to be removed. :return: string removed suffix. Here is the function: def remove_suffix(text: str, suffix: str = None): """ Given a string, removes specified suffix, if it has. >>> remove_suffix('hello world', 'world') 'hello ' >>> remove_suffix('hello world', 'hello ') 'hello world' >>> remove_suffix('NoColumnFoundError', 'Error') 'NoColumnFound' :param text: string from which prefix will be removed. :param suffix: suffix to be removed. :return: string removed suffix. """ if not text or not suffix: return text if not text.endswith(suffix): return text return text[: -len(suffix)]
Given a string, removes specified suffix, if it has. >>> remove_suffix('hello world', 'world') 'hello ' >>> remove_suffix('hello world', 'hello ') 'hello world' >>> remove_suffix('NoColumnFoundError', 'Error') 'NoColumnFound' :param text: string from which prefix will be removed. :param suffix: suffix to be removed. :return: string removed suffix.
4,021
import importlib import inspect import logging import re from dataclasses import asdict, fields, is_dataclass from enum import Enum, EnumMeta from typing import Any, Callable, Dict, List, Union, get_args, get_origin from jinja2 import Environment, meta from promptflow._constants import PF_MAIN_MODULE_NAME from promptflow._core._errors import DuplicateToolMappingError from promptflow._utils.utils import is_json_serializable from promptflow.exceptions import ErrorTarget, UserErrorException from ..contracts.tool import ( ConnectionType, InputDefinition, OutputDefinition, Tool, ToolFuncCallScenario, ToolType, ValueType, ) from ..contracts.types import PromptTemplate def asdict_without_none(obj): return asdict(obj, dict_factory=lambda x: {k: v for (k, v) in x if v})
null
4,022
import importlib import inspect import logging import re from dataclasses import asdict, fields, is_dataclass from enum import Enum, EnumMeta from typing import Any, Callable, Dict, List, Union, get_args, get_origin from jinja2 import Environment, meta from promptflow._constants import PF_MAIN_MODULE_NAME from promptflow._core._errors import DuplicateToolMappingError from promptflow._utils.utils import is_json_serializable from promptflow.exceptions import ErrorTarget, UserErrorException from ..contracts.tool import ( ConnectionType, InputDefinition, OutputDefinition, Tool, ToolFuncCallScenario, ToolType, ValueType, ) from ..contracts.types import PromptTemplate def function_to_interface( f: Callable, initialize_inputs=None, gen_custom_type_conn=False, skip_prompt_template=False ) -> tuple: sign = inspect.signature(f) all_inputs = {} input_defs = {} connection_types = [] # Collect all inputs from class and func if initialize_inputs: if any(k for k in initialize_inputs if k in sign.parameters): raise Exception(f'Duplicate inputs found from {f.__name__!r} and "__init__()"!') all_inputs = {**initialize_inputs} enable_kwargs = any([param.kind == inspect.Parameter.VAR_KEYWORD for _, param in sign.parameters.items()]) all_inputs.update( { k: v for k, v in sign.parameters.items() if k != "self" and v.kind != v.VAR_KEYWORD and v.kind != v.VAR_POSITIONAL # TODO: Handle these cases } ) # Resolve inputs to definitions. for k, v in all_inputs.items(): # Get value type from annotation value_type = resolve_annotation(v.annotation) if skip_prompt_template and value_type is PromptTemplate: # custom llm tool has prompt template as input, skip it continue input_def, is_connection = param_to_definition(v, gen_custom_type_conn=gen_custom_type_conn) input_defs[k] = input_def if is_connection: connection_types.append(input_def.type) # Resolve output to definition typ = resolve_annotation(sign.return_annotation) if typ is inspect.Signature.empty: outputs = {"output": OutputDefinition(type=[ValueType.OBJECT])} elif is_dataclass(typ): outputs = {} for field in fields(typ): outputs[field.name] = OutputDefinition(type=[ValueType.from_type(field.type)]) else: # If the output annotation is a union type, then it should be a list. outputs = { "output": OutputDefinition( type=[ValueType.from_type(t) for t in typ] if isinstance(typ, list) else [ValueType.from_type(typ)] ) } return input_defs, outputs, connection_types, enable_kwargs class Tool: """Tool definition. :param name: The name of the tool :type name: str :param type: The type of the tool :type type: ~promptflow.contracts.tool.ToolType :param inputs: The inputs of the tool :type inputs: Dict[str, ~promptflow.contracts.tool.InputDefinition] :param outputs: The outputs of the tool :type outputs: Optional[Dict[str, ~promptflow.contracts.tool.OutputDefinition]] :param description: The description of the tool :type description: Optional[str] :param module: The module of the tool :type module: Optional[str] :param class_name: The class name of the tool :type class_name: Optional[str] :param source: The source of the tool :type source: Optional[str] :param code: The code of the tool :type code: Optional[str] :param function: The function of the tool :type function: Optional[str] :param connection_type: The connection type of the tool :type connection_type: Optional[List[str]] :param is_builtin: Whether the tool is a built-in tool :type is_builtin: Optional[bool] :param stage: The stage of the tool :type stage: Optional[str] :param enable_kwargs: Whether to enable kwargs, only available for customer python tool :type enable_kwargs: Optional[bool] :param deprecated_tools: A list of old tool IDs that are mapped to the current tool ID. :type deprecated_tools: Optional[List[str]] """ name: str type: ToolType inputs: Dict[str, InputDefinition] outputs: Optional[Dict[str, OutputDefinition]] = None description: Optional[str] = None module: Optional[str] = None class_name: Optional[str] = None source: Optional[str] = None code: Optional[str] = None function: Optional[str] = None connection_type: Optional[List[str]] = None is_builtin: Optional[bool] = None stage: Optional[str] = None enable_kwargs: Optional[bool] = False deprecated_tools: Optional[List[str]] = None def serialize(self) -> dict: """Serialize tool to dict and skip None fields. :return: The serialized tool :rtype: dict """ data = asdict(self, dict_factory=lambda x: {k: v for (k, v) in x if v is not None and k != "outputs"}) if not self.type == ToolType._ACTION: return data # Pop unused field for action skipped_fields = ["type", "inputs", "outputs"] return {k: v for k, v in data.items() if k not in skipped_fields} def deserialize(data: dict) -> "Tool": """Deserialize dict to tool. :param data: The dict needs to be deserialized :type data: dict :return: The deserialized tool :rtype: ~promptflow.contracts.tool.Tool """ return Tool( name=data["name"], description=data.get("description", ""), type=_deserialize_enum(ToolType, data["type"]), inputs={k: InputDefinition.deserialize(i) for k, i in data.get("inputs", {}).items()}, outputs={k: OutputDefinition.deserialize(o) for k, o in data.get("outputs", {}).items()}, module=data.get("module"), class_name=data.get("class_name"), source=data.get("source"), code=data.get("code"), function=data.get("function"), connection_type=data.get("connection_type"), is_builtin=data.get("is_builtin"), stage=data.get("stage"), enable_kwargs=data.get("enable_kwargs", False), deprecated_tools=data.get("deprecated_tools"), ) def _require_connection(self) -> bool: return self.type is ToolType.LLM or isinstance(self.connection_type, list) and len(self.connection_type) > 0 The provided code snippet includes necessary dependencies for implementing the `function_to_tool_definition` function. Write a Python function `def function_to_tool_definition(f: Callable, type=None, initialize_inputs=None) -> Tool` to solve the following problem: Translate a function to tool definition. :param f: Function to be translated. :param type: Tool type :param initialize_inputs: The initialize() func inputs get by get_initialize_inputs() when function defined in class. We will merge those inputs with f() inputs. :return: The tool definition. Here is the function: def function_to_tool_definition(f: Callable, type=None, initialize_inputs=None) -> Tool: """Translate a function to tool definition. :param f: Function to be translated. :param type: Tool type :param initialize_inputs: The initialize() func inputs get by get_initialize_inputs() when function defined in class. We will merge those inputs with f() inputs. :return: The tool definition. """ if hasattr(f, "__original_function"): f = f.__original_function inputs, outputs, _, _ = function_to_interface(f, initialize_inputs) # Hack to get class name class_name = None if "." in f.__qualname__: class_name = f.__qualname__.replace(f".{f.__name__}", "") meta_dict = { "name": f.__qualname__, "description": inspect.getdoc(f) or None, "inputs": inputs, "outputs": outputs, "class_name": class_name, "function": f.__name__, } return Tool(type=type, module=f.__module__, **meta_dict, is_builtin=True, stage="test")
Translate a function to tool definition. :param f: Function to be translated. :param type: Tool type :param initialize_inputs: The initialize() func inputs get by get_initialize_inputs() when function defined in class. We will merge those inputs with f() inputs. :return: The tool definition.
4,023
import importlib import inspect import logging import re from dataclasses import asdict, fields, is_dataclass from enum import Enum, EnumMeta from typing import Any, Callable, Dict, List, Union, get_args, get_origin from jinja2 import Environment, meta from promptflow._constants import PF_MAIN_MODULE_NAME from promptflow._core._errors import DuplicateToolMappingError from promptflow._utils.utils import is_json_serializable from promptflow.exceptions import ErrorTarget, UserErrorException from ..contracts.tool import ( ConnectionType, InputDefinition, OutputDefinition, Tool, ToolFuncCallScenario, ToolType, ValueType, ) from ..contracts.types import PromptTemplate class ValueType(str, Enum): """Value types.""" INT = "int" DOUBLE = "double" BOOL = "bool" STRING = "string" SECRET = "secret" PROMPT_TEMPLATE = "prompt_template" LIST = "list" OBJECT = "object" FILE_PATH = "file_path" IMAGE = "image" ASSISTANT_DEFINITION = "assistant_definition" def from_value(t: Any) -> "ValueType": """Get :class:`~promptflow.contracts.tool.ValueType` by value. :param t: The value needs to get its :class:`~promptflow.contracts.tool.ValueType` :type t: Any :return: The :class:`~promptflow.contracts.tool.ValueType` of the given value :rtype: ~promptflow.contracts.tool.ValueType """ if isinstance(t, Secret): return ValueType.SECRET if isinstance(t, PromptTemplate): return ValueType.PROMPT_TEMPLATE if isinstance(t, bool): return ValueType.BOOL if isinstance(t, int): return ValueType.INT if isinstance(t, float): return ValueType.DOUBLE # FilePath is a subclass of str, so it must be checked before str if isinstance(t, FilePath): return ValueType.FILE_PATH if isinstance(t, str): return ValueType.STRING if isinstance(t, list): return ValueType.LIST if isinstance(t, AssistantDefinition): return ValueType.ASSISTANT_DEFINITION return ValueType.OBJECT def from_type(t: type) -> "ValueType": """Get :class:`~promptflow.contracts.tool.ValueType` by type. :param t: The type needs to get its :class:`~promptflow.contracts.tool.ValueType` :type t: type :return: The :class:`~promptflow.contracts.tool.ValueType` of the given type :rtype: ~promptflow.contracts.tool.ValueType """ if t == int: return ValueType.INT if t == float: return ValueType.DOUBLE if t == bool: return ValueType.BOOL if t == str: return ValueType.STRING if t == list: return ValueType.LIST if t == Secret: return ValueType.SECRET if t == PromptTemplate: return ValueType.PROMPT_TEMPLATE if t == FilePath: return ValueType.FILE_PATH if t == Image: return ValueType.IMAGE if t == AssistantDefinition: return ValueType.ASSISTANT_DEFINITION return ValueType.OBJECT def parse(self, v: Any) -> Any: # noqa: C901 """Parse value to the given :class:`~promptflow.contracts.tool.ValueType`. :param v: The value needs to be parsed to the given :class:`~promptflow.contracts.tool.ValueType` :type v: Any :return: The parsed value :rtype: Any """ if self == ValueType.INT: return int(v) if self == ValueType.DOUBLE: return float(v) if self == ValueType.BOOL: if isinstance(v, bool): return v if isinstance(v, str) and v.lower() in {"true", "false"}: return v.lower() == "true" raise ValueError(f"Invalid boolean value {v!r}") if self == ValueType.STRING: return str(v) if self == ValueType.LIST: if isinstance(v, str): v = json.loads(v) if not isinstance(v, list): raise ValueError(f"Invalid list value {v!r}") return v if self == ValueType.OBJECT: if isinstance(v, str): try: return json.loads(v) except Exception: # Ignore the exception since it might really be a string pass # TODO: parse other types return v class InputDefinition: """Input definition.""" type: List[ValueType] default: str = None description: str = None enum: List[str] = None # Param 'custom_type' is currently used for inputs of custom strong type connection. # For a custom strong type connection input, the type should be 'CustomConnection', # while the custom_type should be the custom strong type connection class name. custom_type: List[str] = None def serialize(self) -> dict: """Serialize input definition to dict. :return: The serialized input definition :rtype: dict """ data = {} data["type"] = [t.value for t in self.type] if len(self.type) == 1: data["type"] = self.type[0].value if self.default: data["default"] = str(self.default) if self.description: data["description"] = self.description if self.enum: data["enum"] = self.enum if self.custom_type: data["custom_type"] = self.custom_type return data def deserialize(data: dict) -> "InputDefinition": """Deserialize dict to input definition. :param data: The dict needs to be deserialized :type data: dict :return: The deserialized input definition :rtype: ~promptflow.contracts.tool.InputDefinition """ def _deserialize_type(v): v = [v] if not isinstance(v, list) else v # Note: Connection type will be keep as string value, # as they may be resolved later after some requisites imported. return [_deserialize_enum(ValueType, item) for item in v] return InputDefinition( _deserialize_type(data["type"]), data.get("default", ""), data.get("description", ""), data.get("enum", []), data.get("custom_type", []), ) def to_flow_input_definition(self): """Used for eager flow to convert input definition to flow input definition.""" from .flow import FlowInputDefinition # TODO: To align with tool resolver we respect the first type if multiple types are provided, # still need more discussion on this. Should we raise error if multiple types are provided? return FlowInputDefinition( type=self.type[0], default=self.default, description=self.description, enum=self.enum ) The provided code snippet includes necessary dependencies for implementing the `get_inputs_for_prompt_template` function. Write a Python function `def get_inputs_for_prompt_template(template_str)` to solve the following problem: Get all input variable names and definitions from a jinja2 template string. : param template_str: template string : type t: str : return: the input name to InputDefinition dict : rtype t: Dict[str, ~promptflow.contracts.tool.InputDefinition] Example: >>> get_inputs_for_prompt_template( template_str="A simple prompt with no variables" ) {} >>> get_inputs_for_prompt_template( template_str="Prompt with only one string input {{str_input}}" ) {"str_input": InputDefinition(type=[ValueType.STRING])} >>> get_inputs_for_prompt_template( template_str="Prompt with image input ![image]({{image_input}}) and string input {{str_input}}" ) {"image_input": InputDefinition(type=[ValueType.IMAGE]), "str_input": InputDefinition(type=[ValueType.STRING]) Here is the function: def get_inputs_for_prompt_template(template_str): """Get all input variable names and definitions from a jinja2 template string. : param template_str: template string : type t: str : return: the input name to InputDefinition dict : rtype t: Dict[str, ~promptflow.contracts.tool.InputDefinition] Example: >>> get_inputs_for_prompt_template( template_str="A simple prompt with no variables" ) {} >>> get_inputs_for_prompt_template( template_str="Prompt with only one string input {{str_input}}" ) {"str_input": InputDefinition(type=[ValueType.STRING])} >>> get_inputs_for_prompt_template( template_str="Prompt with image input ![image]({{image_input}}) and string input {{str_input}}" ) {"image_input": InputDefinition(type=[ValueType.IMAGE]), "str_input": InputDefinition(type=[ValueType.STRING]) """ env = Environment() template = env.parse(template_str) inputs = sorted(meta.find_undeclared_variables(template), key=lambda x: template_str.find(x)) result_dict = {i: InputDefinition(type=[ValueType.STRING]) for i in inputs} # currently we only support image type pattern = r"\!\[(\s*image\s*)\]\(\{\{\s*([^{}]+)\s*\}\}\)" matches = re.finditer(pattern, template_str) for match in matches: input_name = match.group(2).strip() result_dict[input_name] = InputDefinition([ValueType(match.group(1).strip())]) return result_dict
Get all input variable names and definitions from a jinja2 template string. : param template_str: template string : type t: str : return: the input name to InputDefinition dict : rtype t: Dict[str, ~promptflow.contracts.tool.InputDefinition] Example: >>> get_inputs_for_prompt_template( template_str="A simple prompt with no variables" ) {} >>> get_inputs_for_prompt_template( template_str="Prompt with only one string input {{str_input}}" ) {"str_input": InputDefinition(type=[ValueType.STRING])} >>> get_inputs_for_prompt_template( template_str="Prompt with image input ![image]({{image_input}}) and string input {{str_input}}" ) {"image_input": InputDefinition(type=[ValueType.IMAGE]), "str_input": InputDefinition(type=[ValueType.STRING])
4,024
import importlib import inspect import logging import re from dataclasses import asdict, fields, is_dataclass from enum import Enum, EnumMeta from typing import Any, Callable, Dict, List, Union, get_args, get_origin from jinja2 import Environment, meta from promptflow._constants import PF_MAIN_MODULE_NAME from promptflow._core._errors import DuplicateToolMappingError from promptflow._utils.utils import is_json_serializable from promptflow.exceptions import ErrorTarget, UserErrorException from ..contracts.tool import ( ConnectionType, InputDefinition, OutputDefinition, Tool, ToolFuncCallScenario, ToolType, ValueType, ) from ..contracts.types import PromptTemplate class PromptTemplate(str): """This class is used to hint a parameter is a prompt template.""" pass The provided code snippet includes necessary dependencies for implementing the `get_prompt_param_name_from_func` function. Write a Python function `def get_prompt_param_name_from_func(f)` to solve the following problem: Get the param name of prompt template on provider. Here is the function: def get_prompt_param_name_from_func(f): """Get the param name of prompt template on provider.""" return next((k for k, annotation in f.__annotations__.items() if annotation == PromptTemplate), None)
Get the param name of prompt template on provider.
4,025
import importlib import inspect import logging import re from dataclasses import asdict, fields, is_dataclass from enum import Enum, EnumMeta from typing import Any, Callable, Dict, List, Union, get_args, get_origin from jinja2 import Environment, meta from promptflow._constants import PF_MAIN_MODULE_NAME from promptflow._core._errors import DuplicateToolMappingError from promptflow._utils.utils import is_json_serializable from promptflow.exceptions import ErrorTarget, UserErrorException from ..contracts.tool import ( ConnectionType, InputDefinition, OutputDefinition, Tool, ToolFuncCallScenario, ToolType, ValueType, ) from ..contracts.types import PromptTemplate def validate_dynamic_list_func_response_type(response: Any, f: str): class RetrieveToolFuncResultValidationError(RetrieveToolFuncResultError): class ToolFuncCallScenario(str, Enum): def validate_tool_func_result(func_call_scenario: str, result): if func_call_scenario not in list(ToolFuncCallScenario): raise RetrieveToolFuncResultValidationError( f"Invalid tool func call scenario: {func_call_scenario}. " f"Available scenarios are {list(ToolFuncCallScenario)}" ) if func_call_scenario == ToolFuncCallScenario.REVERSE_GENERATED_BY: if not isinstance(result, Dict): raise RetrieveToolFuncResultValidationError( f"ToolFuncCallScenario {func_call_scenario} response must be a dict. " f"{result} is not a dict." ) elif func_call_scenario == ToolFuncCallScenario.DYNAMIC_LIST: validate_dynamic_list_func_response_type(result, f"ToolFuncCallScenario {func_call_scenario}")
null
4,026
import importlib import inspect import logging import re from dataclasses import asdict, fields, is_dataclass from enum import Enum, EnumMeta from typing import Any, Callable, Dict, List, Union, get_args, get_origin from jinja2 import Environment, meta from promptflow._constants import PF_MAIN_MODULE_NAME from promptflow._core._errors import DuplicateToolMappingError from promptflow._utils.utils import is_json_serializable from promptflow.exceptions import ErrorTarget, UserErrorException from ..contracts.tool import ( ConnectionType, InputDefinition, OutputDefinition, Tool, ToolFuncCallScenario, ToolType, ValueType, ) from ..contracts.types import PromptTemplate The provided code snippet includes necessary dependencies for implementing the `append_workspace_triple_to_func_input_params` function. Write a Python function `def append_workspace_triple_to_func_input_params( func_sig_params: Dict, func_input_params_dict: Dict, ws_triple_dict: Dict[str, str] )` to solve the following problem: Append workspace triple to func input params. :param func_sig_params: function signature parameters, full params. :param func_input_params_dict: user input param key-values for dynamic list function. :param ws_triple_dict: workspace triple dict, including subscription_id, resource_group_name, workspace_name. :return: combined func input params. Here is the function: def append_workspace_triple_to_func_input_params( func_sig_params: Dict, func_input_params_dict: Dict, ws_triple_dict: Dict[str, str] ): """Append workspace triple to func input params. :param func_sig_params: function signature parameters, full params. :param func_input_params_dict: user input param key-values for dynamic list function. :param ws_triple_dict: workspace triple dict, including subscription_id, resource_group_name, workspace_name. :return: combined func input params. """ # append workspace triple to func input params if any below condition are met: # 1. func signature has kwargs param. # 2. func signature has param named 'subscription_id','resource_group_name','workspace_name'. ws_triple_dict = ws_triple_dict if ws_triple_dict is not None else {} func_input_params_dict = func_input_params_dict if func_input_params_dict is not None else {} has_kwargs_param = any([param.kind == inspect.Parameter.VAR_KEYWORD for _, param in func_sig_params.items()]) if has_kwargs_param is False: # keep only params that are in func signature. Or run into error when calling func. avail_ws_info_dict = {k: v for k, v in ws_triple_dict.items() if k in set(func_sig_params.keys())} else: avail_ws_info_dict = ws_triple_dict # if ws triple key is in func input params, it means user has provided value for it, # do not expect implicit override. combined_func_input_params = dict(avail_ws_info_dict, **func_input_params_dict) return combined_func_input_params
Append workspace triple to func input params. :param func_sig_params: function signature parameters, full params. :param func_input_params_dict: user input param key-values for dynamic list function. :param ws_triple_dict: workspace triple dict, including subscription_id, resource_group_name, workspace_name. :return: combined func input params.
4,027
import importlib import inspect import logging import re from dataclasses import asdict, fields, is_dataclass from enum import Enum, EnumMeta from typing import Any, Callable, Dict, List, Union, get_args, get_origin from jinja2 import Environment, meta from promptflow._constants import PF_MAIN_MODULE_NAME from promptflow._core._errors import DuplicateToolMappingError from promptflow._utils.utils import is_json_serializable from promptflow.exceptions import ErrorTarget, UserErrorException from ..contracts.tool import ( ConnectionType, InputDefinition, OutputDefinition, Tool, ToolFuncCallScenario, ToolType, ValueType, ) from ..contracts.types import PromptTemplate class FunctionPathValidationError(DynamicListError): pass The provided code snippet includes necessary dependencies for implementing the `load_function_from_function_path` function. Write a Python function `def load_function_from_function_path(func_path: str)` to solve the following problem: Load a function from a function path. The function path should be in the format of "module_name.function_name". Here is the function: def load_function_from_function_path(func_path: str): """Load a function from a function path. The function path should be in the format of "module_name.function_name". """ try: module_name, func_name = func_path.rsplit(".", 1) module = importlib.import_module(module_name) f = getattr(module, func_name) if callable(f): return f else: raise FunctionPathValidationError(f"'{f}' is not callable.") except Exception as e: raise FunctionPathValidationError( f"Failed to parse function from function path: '{func_path}'. Expected format: format 'my_module.my_func'. " f"Detailed error: {e}" )
Load a function from a function path. The function path should be in the format of "module_name.function_name".
4,028
import importlib import inspect import logging import re from dataclasses import asdict, fields, is_dataclass from enum import Enum, EnumMeta from typing import Any, Callable, Dict, List, Union, get_args, get_origin from jinja2 import Environment, meta from promptflow._constants import PF_MAIN_MODULE_NAME from promptflow._core._errors import DuplicateToolMappingError from promptflow._utils.utils import is_json_serializable from promptflow.exceptions import ErrorTarget, UserErrorException from ..contracts.tool import ( ConnectionType, InputDefinition, OutputDefinition, Tool, ToolFuncCallScenario, ToolType, ValueType, ) from ..contracts.types import PromptTemplate UI_HINTS = "ui_hints" def should_preserve_tool_inputs_order(tool_type): """ Currently, we only automatically add input indexes for the custom_llm tool, following the order specified in the tool interface or YAML. As of now, only the custom_llm tool requires the order of its inputs displayed on the UI to be consistent with the order in the YAML, because its inputs are shown in parameter style. To avoid extensive changes, other types of tools will remain as they are. """ return tool_type == ToolType.CUSTOM_LLM The provided code snippet includes necessary dependencies for implementing the `assign_tool_input_index_for_ux_order_if_needed` function. Write a Python function `def assign_tool_input_index_for_ux_order_if_needed(tool)` to solve the following problem: Automatically adds an index to the inputs of a tool based on their order in the tool's YAML. This function directly modifies the tool without returning any value. Example: - tool (dict): A dictionary representing a tool configuration. Inputs do not contain 'ui_hints': { 'name': 'My Custom LLM Tool', 'type': 'custom_llm', 'inputs': { 'input1': {'type': 'string'}, 'input2': {'type': 'string'}, 'input3': {'type': 'string'} } } >>> assign_tool_input_index_for_ux_order_if_needed(tool) - tool (dict): Tool inputs are modified to include 'ui_hints' with an 'index', indicating the order. { 'name': 'My Custom LLM Tool', 'type': 'custom_llm', 'inputs': { 'input1': {'type': 'string', 'ui_hints': {'index': 0}}, 'input2': {'type': 'string', 'ui_hints': {'index': 1}}, 'input3': {'type': 'string', 'ui_hints': {'index': 2}} } } Here is the function: def assign_tool_input_index_for_ux_order_if_needed(tool): """ Automatically adds an index to the inputs of a tool based on their order in the tool's YAML. This function directly modifies the tool without returning any value. Example: - tool (dict): A dictionary representing a tool configuration. Inputs do not contain 'ui_hints': { 'name': 'My Custom LLM Tool', 'type': 'custom_llm', 'inputs': { 'input1': {'type': 'string'}, 'input2': {'type': 'string'}, 'input3': {'type': 'string'} } } >>> assign_tool_input_index_for_ux_order_if_needed(tool) - tool (dict): Tool inputs are modified to include 'ui_hints' with an 'index', indicating the order. { 'name': 'My Custom LLM Tool', 'type': 'custom_llm', 'inputs': { 'input1': {'type': 'string', 'ui_hints': {'index': 0}}, 'input2': {'type': 'string', 'ui_hints': {'index': 1}}, 'input3': {'type': 'string', 'ui_hints': {'index': 2}} } } """ tool_type = tool.get("type") if should_preserve_tool_inputs_order(tool_type) and "inputs" in tool: inputs_dict = tool["inputs"] input_index = 0 # The keys can keep order because the tool YAML is loaded by ruamel.yaml and # ruamel.yaml has the feature of preserving the order of keys. # For more information on ruamel.yaml's feature, please # visit https://yaml.readthedocs.io/en/latest/overview/#overview. for input_name, settings in inputs_dict.items(): # 'uionly_hidden' indicates that the inputs are not the tool's inputs. # They are not displayed on the main interface but appear in a popup window. # These inputs are passed to UX as a list, maintaining the same order as generated by func parameters. # Skip the 'uionly_hidden' input type because the 'ui_hints: index' is not needed. if "input_type" in settings.keys() and settings["input_type"] == "uionly_hidden": continue settings.setdefault(UI_HINTS, {}) settings[UI_HINTS]["index"] = input_index input_index += 1
Automatically adds an index to the inputs of a tool based on their order in the tool's YAML. This function directly modifies the tool without returning any value. Example: - tool (dict): A dictionary representing a tool configuration. Inputs do not contain 'ui_hints': { 'name': 'My Custom LLM Tool', 'type': 'custom_llm', 'inputs': { 'input1': {'type': 'string'}, 'input2': {'type': 'string'}, 'input3': {'type': 'string'} } } >>> assign_tool_input_index_for_ux_order_if_needed(tool) - tool (dict): Tool inputs are modified to include 'ui_hints' with an 'index', indicating the order. { 'name': 'My Custom LLM Tool', 'type': 'custom_llm', 'inputs': { 'input1': {'type': 'string', 'ui_hints': {'index': 0}}, 'input2': {'type': 'string', 'ui_hints': {'index': 1}}, 'input3': {'type': 'string', 'ui_hints': {'index': 2}} } }
4,029
import importlib import inspect import logging import re from dataclasses import asdict, fields, is_dataclass from enum import Enum, EnumMeta from typing import Any, Callable, Dict, List, Union, get_args, get_origin from jinja2 import Environment, meta from promptflow._constants import PF_MAIN_MODULE_NAME from promptflow._core._errors import DuplicateToolMappingError from promptflow._utils.utils import is_json_serializable from promptflow.exceptions import ErrorTarget, UserErrorException from ..contracts.tool import ( ConnectionType, InputDefinition, OutputDefinition, Tool, ToolFuncCallScenario, ToolType, ValueType, ) from ..contracts.types import PromptTemplate _DEPRECATED_TOOLS = "deprecated_tools" def _find_deprecated_tools(package_tools) -> Dict[str, str]: _deprecated_tools = {} for tool_id, tool in package_tools.items(): # a list of old tool IDs that are mapped to the current tool ID. if tool and _DEPRECATED_TOOLS in tool: for old_tool_id in tool[_DEPRECATED_TOOLS]: # throw error to prompt user for manual resolution of this conflict, ensuring secure operation. if old_tool_id in _deprecated_tools: raise DuplicateToolMappingError( message_format=( "The tools '{first_tool_id}', '{second_tool_id}' are both linked to the deprecated " "tool ID '{deprecated_tool_id}'. To ensure secure operation, please either " "remove or adjust one of these tools in your environment and fix this conflict." ), first_tool_id=_deprecated_tools[old_tool_id], second_tool_id=tool_id, deprecated_tool_id=old_tool_id, target=ErrorTarget.TOOL, ) _deprecated_tools[old_tool_id] = tool_id return _deprecated_tools
null
4,030
import importlib import inspect import logging import re from dataclasses import asdict, fields, is_dataclass from enum import Enum, EnumMeta from typing import Any, Callable, Dict, List, Union, get_args, get_origin from jinja2 import Environment, meta from promptflow._constants import PF_MAIN_MODULE_NAME from promptflow._core._errors import DuplicateToolMappingError from promptflow._utils.utils import is_json_serializable from promptflow.exceptions import ErrorTarget, UserErrorException from ..contracts.tool import ( ConnectionType, InputDefinition, OutputDefinition, Tool, ToolFuncCallScenario, ToolType, ValueType, ) from ..contracts.types import PromptTemplate def _get_function_path(function): # Validate function exist if isinstance(function, str): module_name, func_name = function.rsplit(".", 1) module = importlib.import_module(module_name) func = getattr(module, func_name) func_path = function elif isinstance(function, Callable): func = function if function.__module__ == PF_MAIN_MODULE_NAME: func_path = function.__name__ else: func_path = f"{function.__module__}.{function.__name__}" else: raise UserErrorException("Function has invalid type, please provide callable or function name for function.") return func, func_path
null
4,031
import asyncio import contextvars from concurrent.futures import ThreadPoolExecutor from promptflow._utils.utils import set_context def _has_running_loop() -> bool: """Check if the current thread has a running event loop.""" # When using asyncio.get_running_loop(), a RuntimeError is raised if there is no running event loop. # So, we use a try-catch block to determine whether there is currently an event loop in place. # # Note that this is the only way to check whether there is a running loop now, see: # https://docs.python.org/3/library/asyncio-eventloop.html?highlight=get_running_loop#asyncio.get_running_loop try: asyncio.get_running_loop() return True except RuntimeError: return False The provided code snippet includes necessary dependencies for implementing the `async_run_allowing_running_loop` function. Write a Python function `def async_run_allowing_running_loop(async_func, *args, **kwargs)` to solve the following problem: Run an async function in a new thread, allowing the current thread to have a running event loop. When run in an async environment (e.g., in a notebook), because each thread allows only one event loop, using asyncio.run directly leads to a RuntimeError ("asyncio.run() cannot be called from a running event loop"). To address this issue, we add a check for the event loop here. If the current thread already has an event loop, we run _exec_batch in a new thread; otherwise, we run it in the current thread. Here is the function: def async_run_allowing_running_loop(async_func, *args, **kwargs): """Run an async function in a new thread, allowing the current thread to have a running event loop. When run in an async environment (e.g., in a notebook), because each thread allows only one event loop, using asyncio.run directly leads to a RuntimeError ("asyncio.run() cannot be called from a running event loop"). To address this issue, we add a check for the event loop here. If the current thread already has an event loop, we run _exec_batch in a new thread; otherwise, we run it in the current thread. """ if _has_running_loop(): with ThreadPoolExecutor(1, initializer=set_context, initargs=(contextvars.copy_context(),)) as executor: return executor.submit(lambda: asyncio.run(async_func(*args, **kwargs))).result() else: return asyncio.run(async_func(*args, **kwargs))
Run an async function in a new thread, allowing the current thread to have a running event loop. When run in an async environment (e.g., in a notebook), because each thread allows only one event loop, using asyncio.run directly leads to a RuntimeError ("asyncio.run() cannot be called from a running event loop"). To address this issue, we add a check for the event loop here. If the current thread already has an event loop, we run _exec_batch in a new thread; otherwise, we run it in the current thread.
4,032
from typing import AbstractSet, Any, Dict, List, Mapping from promptflow._utils.logger_utils import logger from promptflow.contracts.flow import Flow, FlowInputDefinition, InputAssignment, InputValueType from promptflow.contracts.run_info import FlowRunInfo, Status from promptflow.executor import _input_assignment_parser def apply_default_value_for_input(inputs: Dict[str, FlowInputDefinition], line_inputs: Mapping) -> Dict[str, Any]: updated_inputs = dict(line_inputs or {}) for key, value in inputs.items(): if key not in updated_inputs and (value and value.default is not None): updated_inputs[key] = value.default return updated_inputs
null
4,033
from typing import AbstractSet, Any, Dict, List, Mapping from promptflow._utils.logger_utils import logger from promptflow.contracts.flow import Flow, FlowInputDefinition, InputAssignment, InputValueType from promptflow.contracts.run_info import FlowRunInfo, Status from promptflow.executor import _input_assignment_parser The provided code snippet includes necessary dependencies for implementing the `handle_line_failures` function. Write a Python function `def handle_line_failures(run_infos: List[FlowRunInfo], raise_on_line_failure: bool = False)` to solve the following problem: Handle line failures in batch run Here is the function: def handle_line_failures(run_infos: List[FlowRunInfo], raise_on_line_failure: bool = False): """Handle line failures in batch run""" failed = [i for i, r in enumerate(run_infos) if r.status == Status.Failed] failed_msg = None if len(failed) > 0: failed_indexes = ",".join([str(i) for i in failed]) first_fail_exception = run_infos[failed[0]].error["message"] if raise_on_line_failure: failed_msg = "Flow run failed due to the error: " + first_fail_exception raise Exception(failed_msg) failed_msg = ( f"{len(failed)}/{len(run_infos)} flow run failed, indexes: [{failed_indexes}]," f" exception of index {failed[0]}: {first_fail_exception}" ) logger.error(failed_msg)
Handle line failures in batch run
4,034
from typing import AbstractSet, Any, Dict, List, Mapping from promptflow._utils.logger_utils import logger from promptflow.contracts.flow import Flow, FlowInputDefinition, InputAssignment, InputValueType from promptflow.contracts.run_info import FlowRunInfo, Status from promptflow.executor import _input_assignment_parser The provided code snippet includes necessary dependencies for implementing the `collect_lines` function. Write a Python function `def collect_lines(indexes: List[int], kvs: Mapping[str, List]) -> Mapping[str, List]` to solve the following problem: Collect the values from the kvs according to the indexes. Here is the function: def collect_lines(indexes: List[int], kvs: Mapping[str, List]) -> Mapping[str, List]: """Collect the values from the kvs according to the indexes.""" return {k: [v[i] for i in indexes] for k, v in kvs.items()}
Collect the values from the kvs according to the indexes.
4,035
from typing import AbstractSet, Any, Dict, List, Mapping from promptflow._utils.logger_utils import logger from promptflow.contracts.flow import Flow, FlowInputDefinition, InputAssignment, InputValueType from promptflow.contracts.run_info import FlowRunInfo, Status from promptflow.executor import _input_assignment_parser def get_aggregation_inputs_properties(flow: Flow) -> AbstractSet[str]: """Return the serialized InputAssignment of the aggregation nodes inputs. For example, an aggregation node refers the outputs of a node named "grade", then this function will return set("${grade.output}"). """ normal_node_names = {node.name for node in flow.nodes if flow.is_normal_node(node.name)} properties = set() for node in flow.nodes: if node.name in normal_node_names: continue for value in node.inputs.values(): if not value.value_type == InputValueType.NODE_REFERENCE: continue if value.value in normal_node_names: properties.add(value.serialize()) return properties def _parse_aggregation_input(nodes_outputs: dict, aggregation_input_property: str): """Parse the value of the aggregation input from the nodes outputs.""" assign = InputAssignment.deserialize(aggregation_input_property) return _input_assignment_parser.parse_value(assign, nodes_outputs, {}) The provided code snippet includes necessary dependencies for implementing the `extract_aggregation_inputs` function. Write a Python function `def extract_aggregation_inputs(flow: Flow, nodes_outputs: dict) -> Dict[str, Any]` to solve the following problem: Extract the aggregation inputs of a flow from the nodes outputs. Here is the function: def extract_aggregation_inputs(flow: Flow, nodes_outputs: dict) -> Dict[str, Any]: """Extract the aggregation inputs of a flow from the nodes outputs.""" _aggregation_inputs_references = get_aggregation_inputs_properties(flow) return {prop: _parse_aggregation_input(nodes_outputs, prop) for prop in _aggregation_inputs_references}
Extract the aggregation inputs of a flow from the nodes outputs.
4,036
import contextlib import os import sys The provided code snippet includes necessary dependencies for implementing the `_change_working_dir` function. Write a Python function `def _change_working_dir(path, mkdir=True)` to solve the following problem: Context manager for changing the current working directory Here is the function: def _change_working_dir(path, mkdir=True): """Context manager for changing the current working directory""" saved_path = os.getcwd() if mkdir: os.makedirs(path, exist_ok=True) os.chdir(str(path)) try: yield finally: os.chdir(saved_path)
Context manager for changing the current working directory
4,037
import contextlib import os import sys def inject_sys_path(path): original_sys_path = sys.path.copy() sys.path.insert(0, str(path)) try: yield finally: sys.path = original_sys_path
null
4,038
from dataclasses import dataclass from enum import Enum from typing import Optional class FeatureState(Enum): """The enum of feature state. READY: The feature is ready to use. E2ETEST: The feature is not ready to be shipped to customer and is in e2e testing. """ READY = "Ready" E2ETEST = "E2ETest" class Feature: """The dataclass of feature.""" name: str description: str state: FeatureState component: Optional[str] = "executor" def get_feature_list(): feature_list = [ Feature( name="ActivateConfig", description="Bypass node execution when the node does not meet activate condition.", state=FeatureState.READY, ), Feature( name="Image", description="Support image input and output.", state=FeatureState.READY, ), Feature( name="EnvironmentVariablesInYaml", description="Support environment variables in flow.dag.yaml.", state=FeatureState.READY, ), Feature( name="BatchTimeout", description="Support batch timeout.", state=FeatureState.READY, ), Feature( name="BatchWorkerCount", description="Supports users explicitly specifying the worker count for batch run.", state=FeatureState.READY, ), Feature( name="ResumeBatchRun", description="Support resuming batch run.", state=FeatureState.E2ETEST, ), ] return feature_list
null
4,039
import io import re from jinja2 import Template from .yaml_utils import dump_yaml, load_yaml_string def generate_custom_strong_type_connection_spec(cls, package, package_version): connection_spec = { "connectionCategory": "CustomKeys", "flowValueType": "CustomConnection", "connectionType": cls.__name__, "ConnectionTypeDisplayName": cls.__name__, "configSpecs": [], "module": cls.__module__, "package": package, "package_version": package_version, } for k, typ in cls.__annotations__.items(): spec = { "name": k, "displayName": k.replace("_", " ").title(), "configValueType": typ.__name__, } if hasattr(cls, k): spec["isOptional"] = getattr(cls, k, None) is not None else: spec["isOptional"] = False connection_spec["configSpecs"].append(spec) return connection_spec
null
4,040
import io import re from jinja2 import Template from .yaml_utils import dump_yaml, load_yaml_string def render_comments(connection_template, cls, secrets, configs): if cls.__doc__ is not None: data = load_yaml_string(connection_template) comments_map = extract_comments_mapping(list(secrets) + list(configs), cls.__doc__) # Add comments for secret keys for key in secrets: if key in comments_map.keys(): data["secrets"].yaml_add_eol_comment(comments_map[key] + "\n", key) # Add comments for config keys for key in configs: if key in comments_map.keys(): data["configs"].yaml_add_eol_comment(comments_map[key] + "\n", key) # Dump data object back to string buf = io.StringIO() dump_yaml(data, buf) connection_template_with_comments = buf.getvalue() return connection_template_with_comments return connection_template def generate_custom_strong_type_connection_template(cls, connection_spec, package, package_version): connection_template_str = """ $schema: https://azuremlschemas.azureedge.net/promptflow/latest/CustomStrongTypeConnection.schema.json name: "to_replace_with_connection_name" type: custom custom_type: {{ custom_type }} module: {{ module }} package: {{ package }} package_version: {{ package_version }} configs:{% for key, value in configs.items() %} {{ key }}: "{{ value -}}"{% endfor %} secrets: # must-have{% for key, value in secrets.items() %} {{ key }}: "{{ value -}}"{% endfor %} """ connection_template = Template(connection_template_str) # Extract configs and secrets configs = {} secrets = {} for spec in connection_spec["configSpecs"]: if spec["configValueType"] == "Secret": secrets[spec["name"]] = "to_replace_with_" + spec["name"].replace("-", "_") else: configs[spec["name"]] = getattr(cls, spec["name"], None) or "to_replace_with_" + spec["name"].replace( "-", "_" ) # Prepare data for template data = { "custom_type": cls.__name__, "module": cls.__module__, "package": package, "package_version": package_version, "configs": configs, "secrets": secrets, } connection_template_with_data = connection_template.render(data) connection_template_with_comments = render_comments( connection_template_with_data, cls, secrets.keys(), configs.keys() ) return connection_template_with_comments
null
4,041
import base64 import os import re import uuid from functools import partial from pathlib import Path from typing import Any, Callable, Dict from urllib.parse import urlparse import requests from promptflow._utils._errors import InvalidImageInput, LoadMultimediaDataError from promptflow.contracts.flow import FlowInputDefinition from promptflow.contracts.multimedia import Image, PFBytes from promptflow.contracts.tool import ValueType from promptflow.exceptions import ErrorTarget def get_file_reference_encoder(folder_path: Path, relative_path: Path = None, *, use_absolute_path=False) -> Callable: def pfbytes_file_reference_encoder(obj): """Dumps PFBytes to a file and returns its reference.""" if obj.source_url: return {f"data:{obj._mime_type};url": obj.source_url} if isinstance(obj, PFBytes): file_name = str(uuid.uuid4()) # If use_absolute_path is True, the image file path in image dictionary will be absolute path. return _save_image_to_file(obj, file_name, folder_path, relative_path, use_absolute_path) raise TypeError(f"Not supported to dump type '{type(obj).__name__}'.") return pfbytes_file_reference_encoder def _process_recursively(value: Any, process_funcs: Dict[type, Callable] = None, inplace: bool = False) -> dict: if process_funcs: for cls, f in process_funcs.items(): if isinstance(value, cls): return f(value) if isinstance(value, list): if inplace: for i in range(len(value)): value[i] = _process_recursively(value[i], process_funcs, inplace) else: return [_process_recursively(v, process_funcs, inplace) for v in value] elif isinstance(value, dict): if inplace: for k, v in value.items(): value[k] = _process_recursively(v, process_funcs, inplace) else: return {k: _process_recursively(v, process_funcs, inplace) for k, v in value.items()} return value def persist_multimedia_data(value: Any, base_dir: Path, sub_dir: Path = None): pfbytes_file_reference_encoder = get_file_reference_encoder(base_dir, sub_dir) serialization_funcs = {Image: partial(Image.serialize, **{"encoder": pfbytes_file_reference_encoder})} return _process_recursively(value, process_funcs=serialization_funcs)
null
4,042
import base64 import os import re import uuid from functools import partial from pathlib import Path from typing import Any, Callable, Dict from urllib.parse import urlparse import requests from promptflow._utils._errors import InvalidImageInput, LoadMultimediaDataError from promptflow.contracts.flow import FlowInputDefinition from promptflow.contracts.multimedia import Image, PFBytes from promptflow.contracts.tool import ValueType from promptflow.exceptions import ErrorTarget def _process_recursively(value: Any, process_funcs: Dict[type, Callable] = None, inplace: bool = False) -> dict: def convert_multimedia_data_to_base64(value: Any, with_type=False, dict_type=False): to_base64_funcs = {PFBytes: partial(PFBytes.to_base64, **{"with_type": with_type, "dict_type": dict_type})} return _process_recursively(value, process_funcs=to_base64_funcs)
null
4,043
import base64 import os import re import uuid from functools import partial from pathlib import Path from typing import Any, Callable, Dict from urllib.parse import urlparse import requests from promptflow._utils._errors import InvalidImageInput, LoadMultimediaDataError from promptflow.contracts.flow import FlowInputDefinition from promptflow.contracts.multimedia import Image, PFBytes from promptflow.contracts.tool import ValueType from promptflow.exceptions import ErrorTarget def _process_recursively(value: Any, process_funcs: Dict[type, Callable] = None, inplace: bool = False) -> dict: if process_funcs: for cls, f in process_funcs.items(): if isinstance(value, cls): return f(value) if isinstance(value, list): if inplace: for i in range(len(value)): value[i] = _process_recursively(value[i], process_funcs, inplace) else: return [_process_recursively(v, process_funcs, inplace) for v in value] elif isinstance(value, dict): if inplace: for k, v in value.items(): value[k] = _process_recursively(v, process_funcs, inplace) else: return {k: _process_recursively(v, process_funcs, inplace) for k, v in value.items()} return value def convert_multimedia_data_to_string(value: Any, inplace=False): serialization_funcs = {Image: partial(Image.serialize, **{"encoder": None})} return _process_recursively(value, process_funcs=serialization_funcs, inplace=inplace)
null
4,044
import base64 import os import re import uuid from functools import partial from pathlib import Path from typing import Any, Callable, Dict from urllib.parse import urlparse import requests from promptflow._utils._errors import InvalidImageInput, LoadMultimediaDataError from promptflow.contracts.flow import FlowInputDefinition from promptflow.contracts.multimedia import Image, PFBytes from promptflow.contracts.tool import ValueType from promptflow.exceptions import ErrorTarget def create_image(value: any): def load_multimedia_data_recursively(value: Any): def load_multimedia_data(inputs: Dict[str, FlowInputDefinition], line_inputs: dict): updated_inputs = dict(line_inputs or {}) for key, value in inputs.items(): try: if value.type == ValueType.IMAGE: if isinstance(updated_inputs[key], list): # For aggregation node, the image input is a list. updated_inputs[key] = [create_image(item) for item in updated_inputs[key]] else: updated_inputs[key] = create_image(updated_inputs[key]) elif value.type == ValueType.LIST or value.type == ValueType.OBJECT: updated_inputs[key] = load_multimedia_data_recursively(updated_inputs[key]) except Exception as ex: error_type_and_message = f"({ex.__class__.__name__}) {ex}" raise LoadMultimediaDataError( message_format="Failed to load image for input '{key}': {error_type_and_message}", key=key, error_type_and_message=error_type_and_message, target=ErrorTarget.EXECUTOR, ) from ex return updated_inputs
null
4,045
import base64 import os import re import uuid from functools import partial from pathlib import Path from typing import Any, Callable, Dict from urllib.parse import urlparse import requests from promptflow._utils._errors import InvalidImageInput, LoadMultimediaDataError from promptflow.contracts.flow import FlowInputDefinition from promptflow.contracts.multimedia import Image, PFBytes from promptflow.contracts.tool import ValueType from promptflow.exceptions import ErrorTarget def _process_multimedia_dict_recursively(value: Any, process_func: Callable) -> dict: def resolve_image_path(input_dir: Path, image_dict: dict): def resolve_multimedia_data_recursively(input_dir: Path, value: Any): process_func = partial(resolve_image_path, **{"input_dir": input_dir}) return _process_multimedia_dict_recursively(value, process_func)
null
4,046
from copy import deepcopy from promptflow._core.generator_proxy import GeneratorProxy The provided code snippet includes necessary dependencies for implementing the `_deep_copy_and_extract_items_from_generator_proxy` function. Write a Python function `def _deep_copy_and_extract_items_from_generator_proxy(value: object) -> object` to solve the following problem: Deep copy value, and if there is a GeneratorProxy, deepcopy the items from it. :param value: Any object. :type value: Object :return: Deep copied value. :rtype: Object Here is the function: def _deep_copy_and_extract_items_from_generator_proxy(value: object) -> object: """Deep copy value, and if there is a GeneratorProxy, deepcopy the items from it. :param value: Any object. :type value: Object :return: Deep copied value. :rtype: Object """ if isinstance(value, list): return [_deep_copy_and_extract_items_from_generator_proxy(v) for v in value] elif isinstance(value, dict): return {k: _deep_copy_and_extract_items_from_generator_proxy(v) for k, v in value.items()} elif isinstance(value, GeneratorProxy): return deepcopy(value.items) return deepcopy(value)
Deep copy value, and if there is a GeneratorProxy, deepcopy the items from it. :param value: Any object. :type value: Object :return: Deep copied value. :rtype: Object
4,047
import json import logging import os import sys from contextvars import ContextVar from dataclasses import dataclass from functools import partial from typing import List, Optional from promptflow._constants import PF_LOGGING_LEVEL from promptflow._utils.credential_scrubber import CredentialScrubber from promptflow._utils.exception_utils import ExceptionPresenter from promptflow.contracts.run_mode import RunMode flow_logger = get_logger("execution.flow") bulk_logger = get_logger("execution.bulk") logger = get_logger("execution") def update_single_log_path(log_path: str, logger_: logging.Logger): for wrapper in logger_.handlers: if isinstance(wrapper, FileHandlerConcurrentWrapper): handler: FileHandler = wrapper.handler if handler: wrapper.handler = type(handler)(log_path, handler._formatter) def update_log_path(log_path: str, input_logger: logging.Logger = None): logger_list = [logger, bulk_logger, flow_logger] if input_logger: logger_list.append(input_logger) for logger_ in logger_list: update_single_log_path(log_path, logger_)
null
4,048
import json import logging import os import sys from contextvars import ContextVar from dataclasses import dataclass from functools import partial from typing import List, Optional from promptflow._constants import PF_LOGGING_LEVEL from promptflow._utils.credential_scrubber import CredentialScrubber from promptflow._utils.exception_utils import ExceptionPresenter from promptflow.contracts.run_mode import RunMode class FileHandlerConcurrentWrapper(logging.Handler): """Wrap context-local FileHandler instance for thread safety. A logger instance can write different log to different files in different contexts. """ def __init__(self): super().__init__() self._context_var = ContextVar("handler", default=None) def handler(self) -> FileHandler: return self._context_var.get() def handler(self, handler: FileHandler): self._context_var.set(handler) def emit(self, record: logging.LogRecord): """Override logging.Handler's emit method. Get inner file handler in current context and write log. """ stream_handler: FileHandler = self._context_var.get() if stream_handler is None: return stream_handler.emit(record) def clear(self): """Close file handler and clear context variable.""" handler: FileHandler = self._context_var.get() if handler: try: handler.close() except: # NOQA: E722 # Do nothing if handler close failed. pass self._context_var.set(None) logger = get_logger("execution") The provided code snippet includes necessary dependencies for implementing the `scrub_credentials` function. Write a Python function `def scrub_credentials(s: str)` to solve the following problem: Scrub credentials in string s. For example, for input string: "print accountkey=accountKey", the output will be: "print accountkey=**data_scrubbed**" Here is the function: def scrub_credentials(s: str): """Scrub credentials in string s. For example, for input string: "print accountkey=accountKey", the output will be: "print accountkey=**data_scrubbed**" """ for h in logger.handlers: if isinstance(h, FileHandlerConcurrentWrapper): if h.handler and h.handler._formatter: credential_scrubber = h.handler._formatter.credential_scrubber if credential_scrubber: return credential_scrubber.scrub(s) return CredentialScrubber().scrub(s)
Scrub credentials in string s. For example, for input string: "print accountkey=accountKey", the output will be: "print accountkey=**data_scrubbed**"
4,049
import json import logging import os import sys from contextvars import ContextVar from dataclasses import dataclass from functools import partial from typing import List, Optional from promptflow._constants import PF_LOGGING_LEVEL from promptflow._utils.credential_scrubber import CredentialScrubber from promptflow._utils.exception_utils import ExceptionPresenter from promptflow.contracts.run_mode import RunMode def get_logger(name: str) -> logging.Logger: """Get logger used during execution.""" logger = logging.Logger(name) logger.setLevel(get_pf_logging_level()) logger.addHandler(FileHandlerConcurrentWrapper()) stdout_handler = logging.StreamHandler(sys.stdout) stdout_handler.setFormatter(CredentialScrubberFormatter(fmt=LOG_FORMAT, datefmt=DATETIME_FORMAT)) logger.addHandler(stdout_handler) return logger class LoggerFactory: def get_logger(name: str, verbosity: int = logging.INFO, target_stdout: bool = False): logger = logging.getLogger(name) logger.propagate = False # Set default logger level to debug, we are using handler level to control log by default logger.setLevel(logging.DEBUG) # Use env var at first, then use verbosity verbosity = get_pf_logging_level(default=None) or verbosity if not LoggerFactory._find_handler(logger, logging.StreamHandler): LoggerFactory._add_handler(logger, verbosity, target_stdout) # TODO: Find a more elegant way to set the logging level for azure.core.pipeline.policies._universal azure_logger = logging.getLogger("azure.core.pipeline.policies._universal") azure_logger.setLevel(logging.DEBUG) LoggerFactory._add_handler(azure_logger, logging.DEBUG, target_stdout) return logger def _find_handler(logger: logging.Logger, handler_type: type) -> Optional[logging.Handler]: for log_handler in logger.handlers: if isinstance(log_handler, handler_type): return log_handler return None def _add_handler(logger: logging.Logger, verbosity: int, target_stdout: bool = False) -> None: # set target_stdout=True can log data into sys.stdout instead of default sys.stderr, in this way # logger info and python print result can be synchronized handler = logging.StreamHandler(stream=sys.stdout) if target_stdout else logging.StreamHandler() formatter = logging.Formatter("[%(asctime)s][%(name)s][%(levelname)s] - %(message)s") handler.setFormatter(formatter) handler.setLevel(verbosity) logger.addHandler(handler) The provided code snippet includes necessary dependencies for implementing the `get_cli_sdk_logger` function. Write a Python function `def get_cli_sdk_logger()` to solve the following problem: Get logger used by CLI SDK. Here is the function: def get_cli_sdk_logger(): """Get logger used by CLI SDK.""" # cli sdk logger default logging level is WARNING # here the logger name "promptflow" is from promptflow._sdk._constants.LOGGER_NAME, # to avoid circular import error, use plain string here instead of importing from _constants # because this function is also called in _prepare_home_dir which is in _constants return LoggerFactory.get_logger("promptflow", verbosity=logging.WARNING)
Get logger used by CLI SDK.
4,050
import inspect import json import jsonschema from promptflow._constants import ICON, ICON_DARK, ICON_LIGHT, SKIP_FUNC_PARAMS, TOOL_SCHEMA def _validate_input_settings(tool_inputs, input_settings): """ Check whether input settings of the tool are legitimate. :param tool_inputs: Tool inputs :type tool_inputs: Dict[str, obj] :param input_settings: Input settings of the tool :type input_settings: Dict[str, InputSetting] :param extra_info: Extra info about the tool :type extra_info: Dict[str, obj] :return: Validation result of the tool :rtype: List[str] """ validate_result = [] for input_name, settings in input_settings.items(): if input_name not in tool_inputs: validate_result.append( f"Cannot find {input_name} in tool inputs.", ) if settings.enabled_by and settings.enabled_by not in tool_inputs: validate_result.append(f'Cannot find the input "{settings.enabled_by}" for the enabled_by of {input_name}.') if settings.dynamic_list: dynamic_func_inputs = inspect.signature(settings.dynamic_list._func_obj).parameters has_kwargs = any([param.kind == param.VAR_KEYWORD for param in dynamic_func_inputs.values()]) required_inputs = [ k for k, v in dynamic_func_inputs.items() if v.default is inspect.Parameter.empty and v.kind != v.VAR_KEYWORD and k not in SKIP_FUNC_PARAMS ] if settings.dynamic_list._input_mapping: # Validate input mapping in dynamic_list for func_input, reference_input in settings.dynamic_list._input_mapping.items(): # Check invalid input name of dynamic list function if not has_kwargs and func_input not in dynamic_func_inputs: validate_result.append( f"Cannot find {func_input} in the inputs of " f"dynamic_list func {settings.dynamic_list.func_path}" ) # Check invalid input name of tool if reference_input not in tool_inputs: validate_result.append(f"Cannot find {reference_input} in the tool inputs.") if func_input in required_inputs: required_inputs.remove(func_input) # Check required input of dynamic_list function if len(required_inputs) != 0: validate_result.append(f"Missing required input(s) of dynamic_list function: {required_inputs}") return validate_result The provided code snippet includes necessary dependencies for implementing the `_validate_tool_function` function. Write a Python function `def _validate_tool_function(tool, input_settings, extra_info)` to solve the following problem: Check whether the icon and input settings of the tool are legitimate. :param tool: The tool object :type tool: Tool :param input_settings: Input settings of the tool :type input_settings: Dict[str, InputSetting] :param extra_info: Extra info about the tool :type extra_info: Dict[str, obj] :return: Validation result of the tool :rtype: List[str] Here is the function: def _validate_tool_function(tool, input_settings, extra_info): """ Check whether the icon and input settings of the tool are legitimate. :param tool: The tool object :type tool: Tool :param input_settings: Input settings of the tool :type input_settings: Dict[str, InputSetting] :param extra_info: Extra info about the tool :type extra_info: Dict[str, obj] :return: Validation result of the tool :rtype: List[str] """ validate_result = [] if extra_info: if ICON in extra_info: if ICON_LIGHT in extra_info or ICON_DARK in extra_info: validate_result.append(f"Cannot provide both `icon` and `{ICON_LIGHT}` or `{ICON_DARK}`.") if input_settings: input_settings_validate_result = _validate_input_settings(tool.inputs, input_settings) validate_result.extend(input_settings_validate_result) return validate_result
Check whether the icon and input settings of the tool are legitimate. :param tool: The tool object :type tool: Tool :param input_settings: Input settings of the tool :type input_settings: Dict[str, InputSetting] :param extra_info: Extra info about the tool :type extra_info: Dict[str, obj] :return: Validation result of the tool :rtype: List[str]
4,051
import inspect import json import jsonschema from promptflow._constants import ICON, ICON_DARK, ICON_LIGHT, SKIP_FUNC_PARAMS, TOOL_SCHEMA The provided code snippet includes necessary dependencies for implementing the `_validate_tool_schema` function. Write a Python function `def _validate_tool_schema(tool_dict)` to solve the following problem: Check whether the generated schema of the tool are legitimate. :param tool_dict: The generated tool dict :type tool_dict: Dict[str, obj] :return: Validation result of the tool :rtype: str Here is the function: def _validate_tool_schema(tool_dict): """ Check whether the generated schema of the tool are legitimate. :param tool_dict: The generated tool dict :type tool_dict: Dict[str, obj] :return: Validation result of the tool :rtype: str """ try: with open(TOOL_SCHEMA, "r") as f: tool_schema = json.load(f) jsonschema.validate(instance=tool_dict, schema=tool_schema) except jsonschema.exceptions.ValidationError as e: return str(e)
Check whether the generated schema of the tool are legitimate. :param tool_dict: The generated tool dict :type tool_dict: Dict[str, obj] :return: Validation result of the tool :rtype: str
4,052
import importlib.util import inspect import json import logging import multiprocessing import os import re import types from pathlib import Path from traceback import TracebackException from typing import Mapping from jinja2 import TemplateSyntaxError from jinja2.environment import COMMENT_END_STRING, COMMENT_START_STRING from promptflow._constants import PF_MAIN_MODULE_NAME from promptflow._core._errors import ( GenerateMetaTimeout, MetaFileNotFound, MetaFileReadError, NoToolTypeDefined, NotSupported, ) from promptflow._core.tool import ToolProvider from promptflow._core.tool_settings_parser import _parser_tool_icon, _parser_tool_input_settings from promptflow._core.tool_validation import _validate_tool_function, _validate_tool_schema from promptflow._utils.context_utils import _change_working_dir, inject_sys_path from promptflow._utils.exception_utils import ( ADDITIONAL_INFO_USER_CODE_STACKTRACE, ExceptionPresenter, get_tb_next, last_frame_info, ) from promptflow._utils.process_utils import block_terminate_signal_to_parent from promptflow._utils.tool_utils import asdict_without_none, function_to_interface, get_inputs_for_prompt_template from promptflow.contracts.tool import Tool, ToolType from promptflow.exceptions import ErrorTarget, UserErrorException def generate_python_tools_in_module(module): tool_functions = collect_tool_functions_in_module(module) tool_methods = collect_tool_methods_in_module(module) return [_parse_tool_from_function(f) for f in tool_functions + tool_methods] def generate_python_tools_in_module_as_dict(module): tools = generate_python_tools_in_module(module) return {f"{t.module}.{t.name}": asdict_without_none(t) for t in tools}
null
4,053
import importlib.util import inspect import json import logging import multiprocessing import os import re import types from pathlib import Path from traceback import TracebackException from typing import Mapping from jinja2 import TemplateSyntaxError from jinja2.environment import COMMENT_END_STRING, COMMENT_START_STRING from promptflow._constants import PF_MAIN_MODULE_NAME from promptflow._core._errors import ( GenerateMetaTimeout, MetaFileNotFound, MetaFileReadError, NoToolTypeDefined, NotSupported, ) from promptflow._core.tool import ToolProvider from promptflow._core.tool_settings_parser import _parser_tool_icon, _parser_tool_input_settings from promptflow._core.tool_validation import _validate_tool_function, _validate_tool_schema from promptflow._utils.context_utils import _change_working_dir, inject_sys_path from promptflow._utils.exception_utils import ( ADDITIONAL_INFO_USER_CODE_STACKTRACE, ExceptionPresenter, get_tb_next, last_frame_info, ) from promptflow._utils.process_utils import block_terminate_signal_to_parent from promptflow._utils.tool_utils import asdict_without_none, function_to_interface, get_inputs_for_prompt_template from promptflow.contracts.tool import Tool, ToolType from promptflow.exceptions import ErrorTarget, UserErrorException def generate_python_tool_meta_dict(name, content, source=None): m = load_python_module(content, source) f, initialize_inputs = collect_tool_function_in_module(m) tool = _parse_tool_from_function(f, initialize_inputs=initialize_inputs) extra_info = getattr(f, "__extra_info") input_settings = getattr(f, "__input_settings") tool.module = None if name is not None: tool.name = name if source is None: tool.code = content else: tool.source = source construct_tool, is_invlid_result = _serialize_tool(tool, input_settings, extra_info) if is_invlid_result: raise UserErrorException(f"Tool validation failed: {';'.join(is_invlid_result)}") # Handle string enum in tool dict construct_tool = json.loads(json.dumps(construct_tool)) return construct_tool def generate_python_meta(name, content, source=None): return json.dumps(generate_python_tool_meta_dict(name, content, source), indent=2)
null
4,054
import importlib.util import inspect import json import logging import multiprocessing import os import re import types from pathlib import Path from traceback import TracebackException from typing import Mapping from jinja2 import TemplateSyntaxError from jinja2.environment import COMMENT_END_STRING, COMMENT_START_STRING from promptflow._constants import PF_MAIN_MODULE_NAME from promptflow._core._errors import ( GenerateMetaTimeout, MetaFileNotFound, MetaFileReadError, NoToolTypeDefined, NotSupported, ) from promptflow._core.tool import ToolProvider from promptflow._core.tool_settings_parser import _parser_tool_icon, _parser_tool_input_settings from promptflow._core.tool_validation import _validate_tool_function, _validate_tool_schema from promptflow._utils.context_utils import _change_working_dir, inject_sys_path from promptflow._utils.exception_utils import ( ADDITIONAL_INFO_USER_CODE_STACKTRACE, ExceptionPresenter, get_tb_next, last_frame_info, ) from promptflow._utils.process_utils import block_terminate_signal_to_parent from promptflow._utils.tool_utils import asdict_without_none, function_to_interface, get_inputs_for_prompt_template from promptflow.contracts.tool import Tool, ToolType from promptflow.exceptions import ErrorTarget, UserErrorException def generate_prompt_meta_dict(name, content, prompt_only=False, source=None): def generate_prompt_meta(name, content, prompt_only=False, source=None): return json.dumps(generate_prompt_meta_dict(name, content, prompt_only, source), indent=2)
null
4,055
import importlib.util import inspect import json import logging import multiprocessing import os import re import types from pathlib import Path from traceback import TracebackException from typing import Mapping from jinja2 import TemplateSyntaxError from jinja2.environment import COMMENT_END_STRING, COMMENT_START_STRING from promptflow._constants import PF_MAIN_MODULE_NAME from promptflow._core._errors import ( GenerateMetaTimeout, MetaFileNotFound, MetaFileReadError, NoToolTypeDefined, NotSupported, ) from promptflow._core.tool import ToolProvider from promptflow._core.tool_settings_parser import _parser_tool_icon, _parser_tool_input_settings from promptflow._core.tool_validation import _validate_tool_function, _validate_tool_schema from promptflow._utils.context_utils import _change_working_dir, inject_sys_path from promptflow._utils.exception_utils import ( ADDITIONAL_INFO_USER_CODE_STACKTRACE, ExceptionPresenter, get_tb_next, last_frame_info, ) from promptflow._utils.process_utils import block_terminate_signal_to_parent from promptflow._utils.tool_utils import asdict_without_none, function_to_interface, get_inputs_for_prompt_template from promptflow.contracts.tool import Tool, ToolType from promptflow.exceptions import ErrorTarget, UserErrorException def _generate_tool_meta_and_update_dict( working_dir: Path, tools: Mapping[str, Mapping[str, str]], tool_dict: dict, exception_dict: dict, prevent_terminate_signal_propagation: bool = False, ): if prevent_terminate_signal_propagation: block_terminate_signal_to_parent() _tool_dict, _exception_dict = generate_tool_meta(working_dir, tools) tool_dict.update(_tool_dict) exception_dict.update(_exception_dict) The provided code snippet includes necessary dependencies for implementing the `generate_tool_meta_in_subprocess` function. Write a Python function `def generate_tool_meta_in_subprocess( working_dir: Path, tools: Mapping[str, Mapping[str, str]], input_logger: logging.Logger, timeout: int = 10, prevent_terminate_signal_propagation: bool = False, )` to solve the following problem: :param working_dir: The working directory where the tools are located. :type working_dir: Path :param tools: A dictionary of tool sources and their configurations. :type tools: Mapping[str, Mapping[str, str]] :param input_logger: The logger to log the input. :type input_logger: logging.Logger :param timeout: The timeout in seconds for the subprocess to generate the tool meta. :type timeout: int :param prevent_terminate_signal_propagation: If True, the termination signal of the child process will not be propagated to the parent process. This is to avoid the main process being terminated when the child process is terminated, which is a default behavior within an uvicorn app. :type prevent_terminate_signal_propagation: bool :return: A tuple of dictionaries, containing generated metadata and exceptions on generation. :rtype: Tuple[dict, dict] Here is the function: def generate_tool_meta_in_subprocess( working_dir: Path, tools: Mapping[str, Mapping[str, str]], input_logger: logging.Logger, timeout: int = 10, prevent_terminate_signal_propagation: bool = False, ): """ :param working_dir: The working directory where the tools are located. :type working_dir: Path :param tools: A dictionary of tool sources and their configurations. :type tools: Mapping[str, Mapping[str, str]] :param input_logger: The logger to log the input. :type input_logger: logging.Logger :param timeout: The timeout in seconds for the subprocess to generate the tool meta. :type timeout: int :param prevent_terminate_signal_propagation: If True, the termination signal of the child process will not be propagated to the parent process. This is to avoid the main process being terminated when the child process is terminated, which is a default behavior within an uvicorn app. :type prevent_terminate_signal_propagation: bool :return: A tuple of dictionaries, containing generated metadata and exceptions on generation. :rtype: Tuple[dict, dict] """ manager = multiprocessing.Manager() process_tool_dict = manager.dict() process_exception_dict = manager.dict() p = multiprocessing.Process( target=_generate_tool_meta_and_update_dict, args=(working_dir, tools, process_tool_dict, process_exception_dict, prevent_terminate_signal_propagation), ) p.start() input_logger.info(f"[{os.getpid()}--{p.pid}] Start process to generate tool meta.") p.join(timeout=timeout) if p.is_alive(): input_logger.warning(f"Generate meta timeout after {timeout} seconds, terminate the process.") p.terminate() p.join() # These dict was created by manager.dict(), so convert to normal dict here. tool_dict = {source: tool for source, tool in process_tool_dict.items()} exception_dict = {source: exception for source, exception in process_exception_dict.items()} # For not processed tools, treat as timeout error. for source in tools.keys(): if source not in tool_dict and source not in exception_dict: exception_dict[source] = ExceptionPresenter.create(GenerateMetaTimeout(source=source)).to_dict() return tool_dict, exception_dict
:param working_dir: The working directory where the tools are located. :type working_dir: Path :param tools: A dictionary of tool sources and their configurations. :type tools: Mapping[str, Mapping[str, str]] :param input_logger: The logger to log the input. :type input_logger: logging.Logger :param timeout: The timeout in seconds for the subprocess to generate the tool meta. :type timeout: int :param prevent_terminate_signal_propagation: If True, the termination signal of the child process will not be propagated to the parent process. This is to avoid the main process being terminated when the child process is terminated, which is a default behavior within an uvicorn app. :type prevent_terminate_signal_propagation: bool :return: A tuple of dictionaries, containing generated metadata and exceptions on generation. :rtype: Tuple[dict, dict]
4,056
import importlib.util import inspect import json import logging import multiprocessing import os import re import types from pathlib import Path from traceback import TracebackException from typing import Mapping from jinja2 import TemplateSyntaxError from jinja2.environment import COMMENT_END_STRING, COMMENT_START_STRING from promptflow._constants import PF_MAIN_MODULE_NAME from promptflow._core._errors import ( GenerateMetaTimeout, MetaFileNotFound, MetaFileReadError, NoToolTypeDefined, NotSupported, ) from promptflow._core.tool import ToolProvider from promptflow._core.tool_settings_parser import _parser_tool_icon, _parser_tool_input_settings from promptflow._core.tool_validation import _validate_tool_function, _validate_tool_schema from promptflow._utils.context_utils import _change_working_dir, inject_sys_path from promptflow._utils.exception_utils import ( ADDITIONAL_INFO_USER_CODE_STACKTRACE, ExceptionPresenter, get_tb_next, last_frame_info, ) from promptflow._utils.process_utils import block_terminate_signal_to_parent from promptflow._utils.tool_utils import asdict_without_none, function_to_interface, get_inputs_for_prompt_template from promptflow.contracts.tool import Tool, ToolType from promptflow.exceptions import ErrorTarget, UserErrorException def collect_flow_entry_in_module(m, entry): func_name = entry.split(":")[-1] func = getattr(m, func_name, None) if isinstance(func, types.FunctionType): return func raise PythonLoadError( message_format="Failed to collect flow entry '{entry}' in module '{module}'.", entry=entry, module=m.__name__, ) def _parse_tool_from_function( f, initialize_inputs=None, gen_custom_type_conn=False, skip_prompt_template=False, include_outputs=False ): try: tool_type = getattr(f, "__type", None) or ToolType.PYTHON except Exception as e: raise e tool_name = getattr(f, "__name", None) description = getattr(f, "__description", None) if hasattr(f, "__tool") and isinstance(f.__tool, Tool): return f.__tool if hasattr(f, "__original_function"): f = f.__original_function try: inputs, outputs, _, enable_kwargs = function_to_interface( f, initialize_inputs=initialize_inputs, gen_custom_type_conn=gen_custom_type_conn, skip_prompt_template=skip_prompt_template, ) except Exception as e: error_type_and_message = f"({e.__class__.__name__}) {e}" raise BadFunctionInterface( message_format="Parse interface for tool '{tool_name}' failed: {error_type_and_message}", tool_name=f.__name__, error_type_and_message=error_type_and_message, ) from e class_name = None if "." in f.__qualname__: class_name = f.__qualname__.replace(f".{f.__name__}", "") # Construct the Tool structure return Tool( name=tool_name or f.__qualname__, description=description or inspect.getdoc(f), inputs=inputs, outputs=outputs if include_outputs else None, type=tool_type, class_name=class_name, function=f.__name__, module=f.__module__, enable_kwargs=enable_kwargs, ) def load_python_module_from_file(src_file: Path): # Here we hard code the module name as __pf_main__ since it is invoked as a main script in pf. src_file = Path(src_file).resolve() # Make sure the path is absolute to align with python import behavior. spec = importlib.util.spec_from_file_location(PF_MAIN_MODULE_NAME, location=src_file) if spec is None or spec.loader is None: raise PythonLoaderNotFound( message_format="Failed to load python file '{src_file}'. Please make sure it is a valid .py file.", src_file=src_file, ) m = importlib.util.module_from_spec(spec) try: spec.loader.exec_module(m) except Exception as e: # TODO: add stacktrace to additional info error_type_and_message = f"({e.__class__.__name__}) {e}" raise PythonLoadError( message_format="Failed to load python module from file '{src_file}': {error_type_and_message}", src_file=src_file, error_type_and_message=error_type_and_message, ) from e return m def load_python_module_from_entry(entry: str): try: module_name = entry.split(":")[0] return importlib.import_module(module_name) except Exception as e: error_type_and_message = f"({e.__class__.__name__}) {e}" raise PythonLoadError( message_format="Failed to load python module '{module_name}' from entry '{entry}': " "{error_type_and_message}", module_name=module_name, entry=entry, error_type_and_message=error_type_and_message, ) from e def generate_flow_meta_dict_by_file(entry: str, source: str = None, path: str = None): if path: m = load_python_module_from_file(Path(path)) else: m = load_python_module_from_entry(entry) f = collect_flow_entry_in_module(m, entry) # Since the flow meta is generated from the entry function, we leverage the function # _parse_tool_from_function to parse the interface of the entry function to get the inputs and outputs. tool = _parse_tool_from_function(f, include_outputs=True) flow_meta = {"entry": entry, "function": f.__name__} if source: flow_meta["source"] = source if tool.inputs: flow_meta["inputs"] = {} for k, v in tool.inputs.items(): # We didn't support specifying multiple types for inputs, so we only take the first one. flow_meta["inputs"][k] = {"type": v.type[0].value} if tool.outputs: flow_meta["outputs"] = {} for k, v in tool.outputs.items(): # We didn't support specifying multiple types for outputs, so we only take the first one. flow_meta["outputs"][k] = {"type": v.type[0].value} return flow_meta
null
4,057
import inspect import logging from abc import ABC from dataclasses import InitVar, asdict, dataclass, field from enum import Enum from typing import Callable, Dict, List, Optional, Union from promptflow.tracing._trace import _traced from promptflow.tracing.contracts.trace import TraceType STREAMING_OPTION_PARAMETER_ATTR = "_streaming_option_parameter" class ToolType(str, Enum): LLM = "llm" PYTHON = "python" CSHARP = "csharp" PROMPT = "prompt" _ACTION = "action" CUSTOM_LLM = "custom_llm" The provided code snippet includes necessary dependencies for implementing the `tool` function. Write a Python function `def tool( func=None, *, name: str = None, description: str = None, type: str = None, input_settings=None, streaming_option_parameter: Optional[str] = None, **kwargs, ) -> Callable` to solve the following problem: Decorator for tool functions. The decorated function will be registered as a tool and can be used in a flow. :param name: The tool name. :type name: str :param description: The tool description. :type description: str :param type: The tool type. :type type: str :param input_settings: Dict of input setting. :type input_settings: Dict[str, promptflow.entities.InputSetting] :return: The decorated function. :rtype: Callable Here is the function: def tool( func=None, *, name: str = None, description: str = None, type: str = None, input_settings=None, streaming_option_parameter: Optional[str] = None, **kwargs, ) -> Callable: """Decorator for tool functions. The decorated function will be registered as a tool and can be used in a flow. :param name: The tool name. :type name: str :param description: The tool description. :type description: str :param type: The tool type. :type type: str :param input_settings: Dict of input setting. :type input_settings: Dict[str, promptflow.entities.InputSetting] :return: The decorated function. :rtype: Callable """ def tool_decorator(func: Callable) -> Callable: from promptflow.exceptions import UserErrorException if type is not None and type not in [k.value for k in ToolType]: raise UserErrorException(f"Tool type {type} is not supported yet.") # Calls to tool functions should be traced automatically. new_f = _traced(func, trace_type=TraceType.TOOL) new_f.__tool = None # This will be set when generating the tool definition. new_f.__name = name new_f.__description = description new_f.__type = type new_f.__input_settings = input_settings new_f.__extra_info = kwargs if streaming_option_parameter and isinstance(streaming_option_parameter, str): setattr(new_f, STREAMING_OPTION_PARAMETER_ATTR, streaming_option_parameter) return new_f # enable use decorator without "()" if all arguments are default values if func is not None: return tool_decorator(func) return tool_decorator
Decorator for tool functions. The decorated function will be registered as a tool and can be used in a flow. :param name: The tool name. :type name: str :param description: The tool description. :type description: str :param type: The tool type. :type type: str :param input_settings: Dict of input setting. :type input_settings: Dict[str, promptflow.entities.InputSetting] :return: The decorated function. :rtype: Callable
4,058
import inspect import logging from abc import ABC from dataclasses import InitVar, asdict, dataclass, field from enum import Enum from typing import Callable, Dict, List, Optional, Union from promptflow.tracing._trace import _traced from promptflow.tracing.contracts.trace import TraceType The provided code snippet includes necessary dependencies for implementing the `parse_all_args` function. Write a Python function `def parse_all_args(argnames, args, kwargs) -> dict` to solve the following problem: Parse args + kwargs to kwargs. Here is the function: def parse_all_args(argnames, args, kwargs) -> dict: """Parse args + kwargs to kwargs.""" all_args = {name: value for name, value in zip(argnames, args)} all_args.update(kwargs) return all_args
Parse args + kwargs to kwargs.
4,059
import inspect from typing import Callable class MetricLoggerManager: _instance = None def __init__(self): self._metric_loggers = [] def get_instance() -> "MetricLoggerManager": if MetricLoggerManager._instance is None: MetricLoggerManager._instance = MetricLoggerManager() return MetricLoggerManager._instance def log_metric(self, key, value, variant_id=None): for logger in self._metric_loggers: if len(inspect.signature(logger).parameters) == 2: logger(key, value) # If the logger only accepts two parameters, we don't pass variant_id else: logger(key, value, variant_id) def add_metric_logger(self, logger_func: Callable): existing_logger = next((logger for logger in self._metric_loggers if logger is logger_func), None) if existing_logger: return if not callable(logger_func): return sign = inspect.signature(logger_func) # We accept two kinds of metric loggers: # def log_metric(k, v) # def log_metric(k, v, variant_id) if len(sign.parameters) not in [2, 3]: return self._metric_loggers.append(logger_func) def remove_metric_logger(self, logger_func: Callable): self._metric_loggers.remove(logger_func) The provided code snippet includes necessary dependencies for implementing the `log_metric` function. Write a Python function `def log_metric(key, value, variant_id=None)` to solve the following problem: Log a metric for current promptflow run. :param key: Metric name. :type key: str :param value: Metric value. :type value: float :param variant_id: Variant id for the metric. :type variant_id: str Here is the function: def log_metric(key, value, variant_id=None): """Log a metric for current promptflow run. :param key: Metric name. :type key: str :param value: Metric value. :type value: float :param variant_id: Variant id for the metric. :type variant_id: str """ MetricLoggerManager.get_instance().log_metric(key, value, variant_id)
Log a metric for current promptflow run. :param key: Metric name. :type key: str :param value: Metric value. :type value: float :param variant_id: Variant id for the metric. :type variant_id: str
4,060
import inspect from typing import Callable class MetricLoggerManager: def __init__(self): def get_instance() -> "MetricLoggerManager": def log_metric(self, key, value, variant_id=None): def add_metric_logger(self, logger_func: Callable): def remove_metric_logger(self, logger_func: Callable): def add_metric_logger(logger_func: Callable): MetricLoggerManager.get_instance().add_metric_logger(logger_func)
null
4,061
import inspect from typing import Callable class MetricLoggerManager: _instance = None def __init__(self): self._metric_loggers = [] def get_instance() -> "MetricLoggerManager": if MetricLoggerManager._instance is None: MetricLoggerManager._instance = MetricLoggerManager() return MetricLoggerManager._instance def log_metric(self, key, value, variant_id=None): for logger in self._metric_loggers: if len(inspect.signature(logger).parameters) == 2: logger(key, value) # If the logger only accepts two parameters, we don't pass variant_id else: logger(key, value, variant_id) def add_metric_logger(self, logger_func: Callable): existing_logger = next((logger for logger in self._metric_loggers if logger is logger_func), None) if existing_logger: return if not callable(logger_func): return sign = inspect.signature(logger_func) # We accept two kinds of metric loggers: # def log_metric(k, v) # def log_metric(k, v, variant_id) if len(sign.parameters) not in [2, 3]: return self._metric_loggers.append(logger_func) def remove_metric_logger(self, logger_func: Callable): self._metric_loggers.remove(logger_func) def remove_metric_logger(logger_func: Callable): MetricLoggerManager.get_instance().remove_metric_logger(logger_func)
null
4,062
import hashlib import json from dataclasses import dataclass from typing import Callable, List from promptflow._utils.logger_utils import flow_logger from promptflow.contracts.run_info import RunInfo from promptflow.storage import AbstractCacheStorage, AbstractRunStorage PROMPTFLOW_HASH_ATTR = "__promptflow_hash_func" def get_calculate_cache_func(tool_func): return getattr(tool_func, PROMPTFLOW_HASH_ATTR, None)
null
4,063
import hashlib import json from dataclasses import dataclass from typing import Callable, List from promptflow._utils.logger_utils import flow_logger from promptflow.contracts.run_info import RunInfo from promptflow.storage import AbstractCacheStorage, AbstractRunStorage def set_calculate_cache_func(tool_func, calculate_cache_func): setattr(tool_func, PROMPTFLOW_HASH_ATTR, calculate_cache_func) def enable_cache(calculate_cache_func): def decorator_enable_cache(func): set_calculate_cache_func(func, calculate_cache_func) return func return decorator_enable_cache
null
4,064
import importlib import importlib.util import inspect import logging import traceback import types from functools import partial from pathlib import Path from typing import Callable, Dict, List, Mapping, Optional, Tuple, Union from promptflow._core._errors import ( InputTypeMismatch, InvalidSource, MissingRequiredInputs, PackageToolNotFoundError, ToolLoadError, ) from promptflow._core.tool_meta_generator import ( _parse_tool_from_function, collect_tool_function_in_module, load_python_module_from_file, ) from promptflow._utils.connection_utils import ( generate_custom_strong_type_connection_spec, generate_custom_strong_type_connection_template, ) from promptflow._utils.tool_utils import ( _DEPRECATED_TOOLS, DynamicListError, RetrieveToolFuncResultError, _find_deprecated_tools, append_workspace_triple_to_func_input_params, function_to_tool_definition, get_prompt_param_name_from_func, load_function_from_function_path, validate_dynamic_list_func_response_type, validate_tool_func_result, assign_tool_input_index_for_ux_order_if_needed, ) from promptflow._utils.yaml_utils import load_yaml from promptflow.contracts.flow import InputAssignment, InputValueType, Node, ToolSourceType from promptflow.contracts.tool import ConnectionType, Tool, ToolType from promptflow.exceptions import ErrorTarget, SystemErrorException, UserErrorException, ValidationException def collect_tools_from_directory(base_dir) -> dict: tools = {} for f in Path(base_dir).glob("**/*.yaml"): with open(f, "r") as f: # The feature that automatically assigns indexes to inputs based on their order in the tool YAML, # relying on the feature of ruamel.yaml that maintains key order when load YAML file. # For more information on ruamel.yaml's feature, please # visit https://yaml.readthedocs.io/en/latest/overview/#overview. tools_in_file = load_yaml(f) for identifier, tool in tools_in_file.items(): tools[identifier] = tool return tools
null
4,065
import importlib import importlib.util import inspect import logging import traceback import types from functools import partial from pathlib import Path from typing import Callable, Dict, List, Mapping, Optional, Tuple, Union from promptflow._core._errors import ( InputTypeMismatch, InvalidSource, MissingRequiredInputs, PackageToolNotFoundError, ToolLoadError, ) from promptflow._core.tool_meta_generator import ( _parse_tool_from_function, collect_tool_function_in_module, load_python_module_from_file, ) from promptflow._utils.connection_utils import ( generate_custom_strong_type_connection_spec, generate_custom_strong_type_connection_template, ) from promptflow._utils.tool_utils import ( _DEPRECATED_TOOLS, DynamicListError, RetrieveToolFuncResultError, _find_deprecated_tools, append_workspace_triple_to_func_input_params, function_to_tool_definition, get_prompt_param_name_from_func, load_function_from_function_path, validate_dynamic_list_func_response_type, validate_tool_func_result, assign_tool_input_index_for_ux_order_if_needed, ) from promptflow._utils.yaml_utils import load_yaml from promptflow.contracts.flow import InputAssignment, InputValueType, Node, ToolSourceType from promptflow.contracts.tool import ConnectionType, Tool, ToolType from promptflow.exceptions import ErrorTarget, SystemErrorException, UserErrorException, ValidationException module_logger = logging.getLogger(__name__) PACKAGE_TOOLS_ENTRY = "package_tools" def _get_entry_points_by_group(group): # lazy load to improve performance for scenarios that don't need to load package tools import importlib.metadata # In python3.10 and later, the entry_points() method returns a SelectableView of EntryPoint objects, # which allows us to select entry points by group. In the previous versions, the entry_points() method # returns a dictionary-like object, we can use group name directly as a key. entry_points = importlib.metadata.entry_points() if hasattr(entry_points, "select"): return entry_points.select(group=group) else: return entry_points.get(group, []) The provided code snippet includes necessary dependencies for implementing the `collect_package_tools` function. Write a Python function `def collect_package_tools(keys: Optional[List[str]] = None) -> dict` to solve the following problem: Collect all tools from all installed packages. Here is the function: def collect_package_tools(keys: Optional[List[str]] = None) -> dict: """Collect all tools from all installed packages.""" all_package_tools = {} if keys is not None: keys = set(keys) entry_points = _get_entry_points_by_group(PACKAGE_TOOLS_ENTRY) for entry_point in entry_points: try: list_tool_func = entry_point.load() package_tools = list_tool_func() for identifier, tool in package_tools.items(): # Only load required tools to avoid unnecessary loading when keys is provided if isinstance(keys, set) and identifier not in keys: # Support to collect new tool id if node source tool is a deprecated tool. deprecated_tool_ids = tool.get(_DEPRECATED_TOOLS, []) if not set(deprecated_tool_ids).intersection(keys): continue m = tool["module"] importlib.import_module(m) # Import the module to make sure it is valid tool["package"] = entry_point.dist.metadata["Name"] tool["package_version"] = entry_point.dist.version assign_tool_input_index_for_ux_order_if_needed(tool) all_package_tools[identifier] = tool except Exception as e: msg = ( f"Failed to load tools from package {entry_point.dist.metadata['Name']}: {e}," + f" traceback: {traceback.format_exc()}" ) module_logger.warning(msg) return all_package_tools
Collect all tools from all installed packages.
4,066
import importlib import importlib.util import inspect import logging import traceback import types from functools import partial from pathlib import Path from typing import Callable, Dict, List, Mapping, Optional, Tuple, Union from promptflow._core._errors import ( InputTypeMismatch, InvalidSource, MissingRequiredInputs, PackageToolNotFoundError, ToolLoadError, ) from promptflow._core.tool_meta_generator import ( _parse_tool_from_function, collect_tool_function_in_module, load_python_module_from_file, ) from promptflow._utils.connection_utils import ( generate_custom_strong_type_connection_spec, generate_custom_strong_type_connection_template, ) from promptflow._utils.tool_utils import ( _DEPRECATED_TOOLS, DynamicListError, RetrieveToolFuncResultError, _find_deprecated_tools, append_workspace_triple_to_func_input_params, function_to_tool_definition, get_prompt_param_name_from_func, load_function_from_function_path, validate_dynamic_list_func_response_type, validate_tool_func_result, assign_tool_input_index_for_ux_order_if_needed, ) from promptflow._utils.yaml_utils import load_yaml from promptflow.contracts.flow import InputAssignment, InputValueType, Node, ToolSourceType from promptflow.contracts.tool import ConnectionType, Tool, ToolType from promptflow.exceptions import ErrorTarget, SystemErrorException, UserErrorException, ValidationException module_logger = logging.getLogger(__name__) PACKAGE_TOOLS_ENTRY = "package_tools" def _get_entry_points_by_group(group): # lazy load to improve performance for scenarios that don't need to load package tools import importlib.metadata # In python3.10 and later, the entry_points() method returns a SelectableView of EntryPoint objects, # which allows us to select entry points by group. In the previous versions, the entry_points() method # returns a dictionary-like object, we can use group name directly as a key. entry_points = importlib.metadata.entry_points() if hasattr(entry_points, "select"): return entry_points.select(group=group) else: return entry_points.get(group, []) The provided code snippet includes necessary dependencies for implementing the `collect_package_tools_and_connections` function. Write a Python function `def collect_package_tools_and_connections(keys: Optional[List[str]] = None) -> dict` to solve the following problem: Collect all tools and custom strong type connections from all installed packages. Here is the function: def collect_package_tools_and_connections(keys: Optional[List[str]] = None) -> dict: """Collect all tools and custom strong type connections from all installed packages.""" all_package_tools = {} all_package_connection_specs = {} all_package_connection_templates = {} if keys is not None: keys = set(keys) entry_points = _get_entry_points_by_group(PACKAGE_TOOLS_ENTRY) for entry_point in entry_points: try: list_tool_func = entry_point.load() package_tools = list_tool_func() for identifier, tool in package_tools.items(): # Only load required tools to avoid unnecessary loading when keys is provided if isinstance(keys, set) and identifier not in keys: continue m = tool["module"] module = importlib.import_module(m) # Import the module to make sure it is valid tool["package"] = entry_point.dist.metadata["Name"] tool["package_version"] = entry_point.dist.version assign_tool_input_index_for_ux_order_if_needed(tool) all_package_tools[identifier] = tool # Get custom strong type connection definition custom_strong_type_connections_classes = [ obj for name, obj in inspect.getmembers(module) if inspect.isclass(obj) and ConnectionType.is_custom_strong_type(obj) and (not ConnectionType.is_connection_class_name(name)) ] if custom_strong_type_connections_classes: for cls in custom_strong_type_connections_classes: identifier = f"{cls.__module__}.{cls.__name__}" connection_spec = generate_custom_strong_type_connection_spec( cls, entry_point.dist.metadata["Name"], entry_point.dist.version ) all_package_connection_specs[identifier] = connection_spec all_package_connection_templates[identifier] = generate_custom_strong_type_connection_template( cls, connection_spec, entry_point.dist.metadata["Name"], entry_point.dist.version ) except Exception as e: msg = ( f"Failed to load tools from package {entry_point.dist.metadata['Name']}: {e}," + f" traceback: {traceback.format_exc()}" ) module_logger.warning(msg) return all_package_tools, all_package_connection_specs, all_package_connection_templates
Collect all tools and custom strong type connections from all installed packages.
4,067
import importlib import importlib.util import inspect import logging import traceback import types from functools import partial from pathlib import Path from typing import Callable, Dict, List, Mapping, Optional, Tuple, Union from promptflow._core._errors import ( InputTypeMismatch, InvalidSource, MissingRequiredInputs, PackageToolNotFoundError, ToolLoadError, ) from promptflow._core.tool_meta_generator import ( _parse_tool_from_function, collect_tool_function_in_module, load_python_module_from_file, ) from promptflow._utils.connection_utils import ( generate_custom_strong_type_connection_spec, generate_custom_strong_type_connection_template, ) from promptflow._utils.tool_utils import ( _DEPRECATED_TOOLS, DynamicListError, RetrieveToolFuncResultError, _find_deprecated_tools, append_workspace_triple_to_func_input_params, function_to_tool_definition, get_prompt_param_name_from_func, load_function_from_function_path, validate_dynamic_list_func_response_type, validate_tool_func_result, assign_tool_input_index_for_ux_order_if_needed, ) from promptflow._utils.yaml_utils import load_yaml from promptflow.contracts.flow import InputAssignment, InputValueType, Node, ToolSourceType from promptflow.contracts.tool import ConnectionType, Tool, ToolType from promptflow.exceptions import ErrorTarget, SystemErrorException, UserErrorException, ValidationException module_logger = logging.getLogger(__name__) def retrieve_tool_func_result( func_call_scenario: str, func_path: str, func_input_params_dict: Dict, ws_triple_dict: Dict[str, str] = {} ): func = load_function_from_function_path(func_path) # get param names from func signature. func_sig_params = inspect.signature(func).parameters module_logger.warning(f"func_sig_params of func_path is: '{func_sig_params}'") module_logger.warning(f"func_input_params_dict is: '{func_input_params_dict}'") # Append workspace triple to func input params if func signature has kwargs param. # Or append ws_triple_dict params that are in func signature. combined_func_input_params = append_workspace_triple_to_func_input_params( func_sig_params, func_input_params_dict, ws_triple_dict ) try: result = func(**combined_func_input_params) except Exception as e: raise RetrieveToolFuncResultError(f"Error when calling function {func_path}: {e}") validate_tool_func_result(func_call_scenario, result) return result
null
4,068
import importlib import importlib.util import inspect import logging import traceback import types from functools import partial from pathlib import Path from typing import Callable, Dict, List, Mapping, Optional, Tuple, Union from promptflow._core._errors import ( InputTypeMismatch, InvalidSource, MissingRequiredInputs, PackageToolNotFoundError, ToolLoadError, ) from promptflow._core.tool_meta_generator import ( _parse_tool_from_function, collect_tool_function_in_module, load_python_module_from_file, ) from promptflow._utils.connection_utils import ( generate_custom_strong_type_connection_spec, generate_custom_strong_type_connection_template, ) from promptflow._utils.tool_utils import ( _DEPRECATED_TOOLS, DynamicListError, RetrieveToolFuncResultError, _find_deprecated_tools, append_workspace_triple_to_func_input_params, function_to_tool_definition, get_prompt_param_name_from_func, load_function_from_function_path, validate_dynamic_list_func_response_type, validate_tool_func_result, assign_tool_input_index_for_ux_order_if_needed, ) from promptflow._utils.yaml_utils import load_yaml from promptflow.contracts.flow import InputAssignment, InputValueType, Node, ToolSourceType from promptflow.contracts.tool import ConnectionType, Tool, ToolType from promptflow.exceptions import ErrorTarget, SystemErrorException, UserErrorException, ValidationException module_logger = logging.getLogger(__name__) def gen_dynamic_list(func_path: str, func_input_params_dict: Dict, ws_triple_dict: Dict[str, str] = {}): func = load_function_from_function_path(func_path) # get param names from func signature. func_sig_params = inspect.signature(func).parameters module_logger.warning(f"func_sig_params of func_path is: '{func_sig_params}'") module_logger.warning(f"func_input_params_dict is: '{func_input_params_dict}'") combined_func_input_params = append_workspace_triple_to_func_input_params( func_sig_params, func_input_params_dict, ws_triple_dict ) try: result = func(**combined_func_input_params) except Exception as e: raise DynamicListError(f"Error when calling function {func_path}: {e}") # validate response is of required format. Throw correct message if response is empty. validate_dynamic_list_func_response_type(result, func.__name__) return result
null
4,069
import importlib import importlib.util import inspect import logging import traceback import types from functools import partial from pathlib import Path from typing import Callable, Dict, List, Mapping, Optional, Tuple, Union from promptflow._core._errors import ( InputTypeMismatch, InvalidSource, MissingRequiredInputs, PackageToolNotFoundError, ToolLoadError, ) from promptflow._core.tool_meta_generator import ( _parse_tool_from_function, collect_tool_function_in_module, load_python_module_from_file, ) from promptflow._utils.connection_utils import ( generate_custom_strong_type_connection_spec, generate_custom_strong_type_connection_template, ) from promptflow._utils.tool_utils import ( _DEPRECATED_TOOLS, DynamicListError, RetrieveToolFuncResultError, _find_deprecated_tools, append_workspace_triple_to_func_input_params, function_to_tool_definition, get_prompt_param_name_from_func, load_function_from_function_path, validate_dynamic_list_func_response_type, validate_tool_func_result, assign_tool_input_index_for_ux_order_if_needed, ) from promptflow._utils.yaml_utils import load_yaml from promptflow.contracts.flow import InputAssignment, InputValueType, Node, ToolSourceType from promptflow.contracts.tool import ConnectionType, Tool, ToolType from promptflow.exceptions import ErrorTarget, SystemErrorException, UserErrorException, ValidationException builtins = {} def _register(provider_cls, collection, type): from promptflow._core.tool import ToolProvider if not issubclass(provider_cls, ToolProvider): raise Exception(f"Class {provider_cls.__name__!r} must be a subclass of promptflow.ToolProvider.") initialize_inputs = provider_cls.get_initialize_inputs() # Build tool/provider definition for name, value in provider_cls.__dict__.items(): if hasattr(value, "__original_function"): name = value.__original_function.__qualname__ value.__tool = function_to_tool_definition(value, type=type, initialize_inputs=initialize_inputs) collection[name] = value.__tool module_logger.debug(f"Registered {name} as a builtin function") # Get the connection type - provider name mapping for execution use # Tools/Providers related connection must have been imported for param in initialize_inputs.values(): if not param.annotation: continue annotation_type_name = param.annotation.__name__ if annotation_type_name in connections: api_name = provider_cls.__name__ module_logger.debug(f"Add connection type {annotation_type_name} to api {api_name} mapping") connection_type_to_api_mapping[annotation_type_name] = api_name break def register_builtins(provider_cls): _register(provider_cls, builtins, ToolType.PYTHON)
null
4,070
import importlib import importlib.util import inspect import logging import traceback import types from functools import partial from pathlib import Path from typing import Callable, Dict, List, Mapping, Optional, Tuple, Union from promptflow._core._errors import ( InputTypeMismatch, InvalidSource, MissingRequiredInputs, PackageToolNotFoundError, ToolLoadError, ) from promptflow._core.tool_meta_generator import ( _parse_tool_from_function, collect_tool_function_in_module, load_python_module_from_file, ) from promptflow._utils.connection_utils import ( generate_custom_strong_type_connection_spec, generate_custom_strong_type_connection_template, ) from promptflow._utils.tool_utils import ( _DEPRECATED_TOOLS, DynamicListError, RetrieveToolFuncResultError, _find_deprecated_tools, append_workspace_triple_to_func_input_params, function_to_tool_definition, get_prompt_param_name_from_func, load_function_from_function_path, validate_dynamic_list_func_response_type, validate_tool_func_result, assign_tool_input_index_for_ux_order_if_needed, ) from promptflow._utils.yaml_utils import load_yaml from promptflow.contracts.flow import InputAssignment, InputValueType, Node, ToolSourceType from promptflow.contracts.tool import ConnectionType, Tool, ToolType from promptflow.exceptions import ErrorTarget, SystemErrorException, UserErrorException, ValidationException apis = {} def _register(provider_cls, collection, type): from promptflow._core.tool import ToolProvider if not issubclass(provider_cls, ToolProvider): raise Exception(f"Class {provider_cls.__name__!r} must be a subclass of promptflow.ToolProvider.") initialize_inputs = provider_cls.get_initialize_inputs() # Build tool/provider definition for name, value in provider_cls.__dict__.items(): if hasattr(value, "__original_function"): name = value.__original_function.__qualname__ value.__tool = function_to_tool_definition(value, type=type, initialize_inputs=initialize_inputs) collection[name] = value.__tool module_logger.debug(f"Registered {name} as a builtin function") # Get the connection type - provider name mapping for execution use # Tools/Providers related connection must have been imported for param in initialize_inputs.values(): if not param.annotation: continue annotation_type_name = param.annotation.__name__ if annotation_type_name in connections: api_name = provider_cls.__name__ module_logger.debug(f"Add connection type {annotation_type_name} to api {api_name} mapping") connection_type_to_api_mapping[annotation_type_name] = api_name break def register_apis(provider_cls): _register(provider_cls, apis, ToolType._ACTION)
null
4,071
import importlib import importlib.util import inspect import logging import traceback import types from functools import partial from pathlib import Path from typing import Callable, Dict, List, Mapping, Optional, Tuple, Union from promptflow._core._errors import ( InputTypeMismatch, InvalidSource, MissingRequiredInputs, PackageToolNotFoundError, ToolLoadError, ) from promptflow._core.tool_meta_generator import ( _parse_tool_from_function, collect_tool_function_in_module, load_python_module_from_file, ) from promptflow._utils.connection_utils import ( generate_custom_strong_type_connection_spec, generate_custom_strong_type_connection_template, ) from promptflow._utils.tool_utils import ( _DEPRECATED_TOOLS, DynamicListError, RetrieveToolFuncResultError, _find_deprecated_tools, append_workspace_triple_to_func_input_params, function_to_tool_definition, get_prompt_param_name_from_func, load_function_from_function_path, validate_dynamic_list_func_response_type, validate_tool_func_result, assign_tool_input_index_for_ux_order_if_needed, ) from promptflow._utils.yaml_utils import load_yaml from promptflow.contracts.flow import InputAssignment, InputValueType, Node, ToolSourceType from promptflow.contracts.tool import ConnectionType, Tool, ToolType from promptflow.exceptions import ErrorTarget, SystemErrorException, UserErrorException, ValidationException builtins = {} def _register_method(provider_method, collection, type): name = provider_method.__qualname__ provider_method.__tool = function_to_tool_definition(provider_method, type=type) collection[name] = provider_method.__tool module_logger.debug(f"Registered {name} as {type} function") def register_builtin_method(provider_method): _register_method(provider_method, builtins, ToolType.PYTHON)
null
4,072
import importlib import importlib.util import inspect import logging import traceback import types from functools import partial from pathlib import Path from typing import Callable, Dict, List, Mapping, Optional, Tuple, Union from promptflow._core._errors import ( InputTypeMismatch, InvalidSource, MissingRequiredInputs, PackageToolNotFoundError, ToolLoadError, ) from promptflow._core.tool_meta_generator import ( _parse_tool_from_function, collect_tool_function_in_module, load_python_module_from_file, ) from promptflow._utils.connection_utils import ( generate_custom_strong_type_connection_spec, generate_custom_strong_type_connection_template, ) from promptflow._utils.tool_utils import ( _DEPRECATED_TOOLS, DynamicListError, RetrieveToolFuncResultError, _find_deprecated_tools, append_workspace_triple_to_func_input_params, function_to_tool_definition, get_prompt_param_name_from_func, load_function_from_function_path, validate_dynamic_list_func_response_type, validate_tool_func_result, assign_tool_input_index_for_ux_order_if_needed, ) from promptflow._utils.yaml_utils import load_yaml from promptflow.contracts.flow import InputAssignment, InputValueType, Node, ToolSourceType from promptflow.contracts.tool import ConnectionType, Tool, ToolType from promptflow.exceptions import ErrorTarget, SystemErrorException, UserErrorException, ValidationException apis = {} def _register_method(provider_method, collection, type): name = provider_method.__qualname__ provider_method.__tool = function_to_tool_definition(provider_method, type=type) collection[name] = provider_method.__tool module_logger.debug(f"Registered {name} as {type} function") def register_api_method(provider_method): _register_method(provider_method, apis, ToolType._ACTION)
null
4,073
import importlib import importlib.util import inspect import logging import traceback import types from functools import partial from pathlib import Path from typing import Callable, Dict, List, Mapping, Optional, Tuple, Union from promptflow._core._errors import ( InputTypeMismatch, InvalidSource, MissingRequiredInputs, PackageToolNotFoundError, ToolLoadError, ) from promptflow._core.tool_meta_generator import ( _parse_tool_from_function, collect_tool_function_in_module, load_python_module_from_file, ) from promptflow._utils.connection_utils import ( generate_custom_strong_type_connection_spec, generate_custom_strong_type_connection_template, ) from promptflow._utils.tool_utils import ( _DEPRECATED_TOOLS, DynamicListError, RetrieveToolFuncResultError, _find_deprecated_tools, append_workspace_triple_to_func_input_params, function_to_tool_definition, get_prompt_param_name_from_func, load_function_from_function_path, validate_dynamic_list_func_response_type, validate_tool_func_result, assign_tool_input_index_for_ux_order_if_needed, ) from promptflow._utils.yaml_utils import load_yaml from promptflow.contracts.flow import InputAssignment, InputValueType, Node, ToolSourceType from promptflow.contracts.tool import ConnectionType, Tool, ToolType from promptflow.exceptions import ErrorTarget, SystemErrorException, UserErrorException, ValidationException connections = {} def register_connections(connection_classes: Union[type, List[type]]): connection_classes = [connection_classes] if not isinstance(connection_classes, list) else connection_classes connections.update({cls.__name__: cls for cls in connection_classes})
null
4,074
import io from pathlib import Path from promptflow._constants import ICON, ICON_DARK, ICON_LIGHT from promptflow._utils.multimedia_utils import convert_multimedia_data_to_base64 from promptflow._utils.tool_utils import asdict_without_none from promptflow.contracts.multimedia import Image from promptflow.exceptions import UserErrorException The provided code snippet includes necessary dependencies for implementing the `_parser_tool_input_settings` function. Write a Python function `def _parser_tool_input_settings(tool_inputs, input_settings)` to solve the following problem: Parser input settings to dict :param tool_inputs: Tool inputs :type tool_inputs: Dict[str, obj] :param input_settings: Input settings of the tool :type input_settings: Dict[str, obj] Here is the function: def _parser_tool_input_settings(tool_inputs, input_settings): """ Parser input settings to dict :param tool_inputs: Tool inputs :type tool_inputs: Dict[str, obj] :param input_settings: Input settings of the tool :type input_settings: Dict[str, obj] """ generated_by_inputs = {} for input_name, settings in input_settings.items(): tool_inputs[input_name].update(asdict_without_none(settings)) kwargs = settings._kwargs or {} for k, v in kwargs.items(): if k in tool_inputs[input_name]: if isinstance(v, dict): tool_inputs[input_name][k].update(v) elif isinstance(v, list): tool_inputs[input_name][k].append(v) else: tool_inputs[input_name][k] = v else: tool_inputs[input_name][k] = v if settings.generated_by: generated_by_inputs.update(settings.generated_by._input_settings) tool_inputs.update(generated_by_inputs)
Parser input settings to dict :param tool_inputs: Tool inputs :type tool_inputs: Dict[str, obj] :param input_settings: Input settings of the tool :type input_settings: Dict[str, obj]