id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
4,075 | 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
def _serialize_icon_data(icon):
if not Path(icon).exists():
raise UserErrorException(f"Cannot find the icon path {icon}.")
return _serialize_image_data(icon)
The provided code snippet includes necessary dependencies for implementing the `_parser_tool_icon` function. Write a Python function `def _parser_tool_icon(extra_info)` to solve the following problem:
parser tool icon to base64.
Here is the function:
def _parser_tool_icon(extra_info):
"""parser tool icon to base64."""
if ICON in extra_info:
extra_info[ICON] = _serialize_icon_data(extra_info[ICON])
if ICON_LIGHT in extra_info:
icon = extra_info.get(ICON, {})
icon["light"] = _serialize_icon_data(extra_info.pop(ICON_LIGHT))
extra_info[ICON] = icon
if ICON_DARK in extra_info:
icon = extra_info.get(ICON, {})
icon["dark"] = _serialize_icon_data(extra_info.pop(ICON_DARK))
extra_info[ICON] = icon
return extra_info | parser tool icon to base64. |
4,076 | class GeneratorProxy:
"""A proxy for generator that can record all items that have been yielded from the generator."""
def __init__(self, generator):
self._generator = generator
self._items = []
def __iter__(self):
return self
def __next__(self):
item = next(self._generator)
self._items.append(item)
return item
def items(self):
return self._items
def generate_from_proxy(proxy: GeneratorProxy):
yield from proxy | null |
4,077 | import collections
import datetime
import hashlib
import json
import multiprocessing
import os
import platform
import re
import shutil
import stat
import sys
import tempfile
import uuid
import zipfile
from contextlib import contextmanager
from enum import Enum
from functools import partial
from os import PathLike
from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Tuple, Union
from urllib.parse import urlparse
import keyring
import pydash
from cryptography.fernet import Fernet
from filelock import FileLock
from jinja2 import Template
from keyring.errors import NoKeyringError
from marshmallow import ValidationError
import promptflow
from promptflow._constants import EXTENSION_UA, PF_NO_INTERACTIVE_LOGIN, PF_USER_AGENT, USER_AGENT
from promptflow._sdk._constants import (
AZURE_WORKSPACE_REGEX_FORMAT,
DAG_FILE_NAME,
DEFAULT_ENCODING,
FLOW_META_JSON,
FLOW_META_JSON_GEN_TIMEOUT,
FLOW_TOOLS_JSON,
FLOW_TOOLS_JSON_GEN_TIMEOUT,
HOME_PROMPT_FLOW_DIR,
KEYRING_ENCRYPTION_KEY_NAME,
KEYRING_ENCRYPTION_LOCK_PATH,
KEYRING_SYSTEM,
NODE,
NODE_VARIANTS,
NODES,
PROMPT_FLOW_DIR_NAME,
REFRESH_CONNECTIONS_DIR_LOCK_PATH,
REGISTRY_URI_PREFIX,
REMOTE_URI_PREFIX,
USE_VARIANTS,
VARIANTS,
AzureMLWorkspaceTriad,
CommonYamlFields,
)
from promptflow._sdk._errors import (
DecryptConnectionError,
GenerateFlowMetaJsonError,
GenerateFlowToolsJsonError,
StoreConnectionEncryptionKeyError,
UnsecureConnectionError,
)
from promptflow._sdk._vendor import IgnoreFile, get_ignore_file, get_upload_files_from_folder
from promptflow._utils.context_utils import _change_working_dir, inject_sys_path
from promptflow._utils.dataclass_serializer import serialize
from promptflow._utils.logger_utils import get_cli_sdk_logger
from promptflow._utils.utils import _match_reference
from promptflow._utils.yaml_utils import dump_yaml, load_yaml, load_yaml_string
from promptflow.contracts.tool import ToolType
from promptflow.exceptions import ErrorTarget, UserErrorException
def find_type_in_override(params_override: Optional[list] = None) -> Optional[str]:
params_override = params_override or []
for override in params_override:
if CommonYamlFields.TYPE in override:
return override[CommonYamlFields.TYPE]
return None | null |
4,078 | import collections
import datetime
import hashlib
import json
import multiprocessing
import os
import platform
import re
import shutil
import stat
import sys
import tempfile
import uuid
import zipfile
from contextlib import contextmanager
from enum import Enum
from functools import partial
from os import PathLike
from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Tuple, Union
from urllib.parse import urlparse
import keyring
import pydash
from cryptography.fernet import Fernet
from filelock import FileLock
from jinja2 import Template
from keyring.errors import NoKeyringError
from marshmallow import ValidationError
import promptflow
from promptflow._constants import EXTENSION_UA, PF_NO_INTERACTIVE_LOGIN, PF_USER_AGENT, USER_AGENT
from promptflow._sdk._constants import (
AZURE_WORKSPACE_REGEX_FORMAT,
DAG_FILE_NAME,
DEFAULT_ENCODING,
FLOW_META_JSON,
FLOW_META_JSON_GEN_TIMEOUT,
FLOW_TOOLS_JSON,
FLOW_TOOLS_JSON_GEN_TIMEOUT,
HOME_PROMPT_FLOW_DIR,
KEYRING_ENCRYPTION_KEY_NAME,
KEYRING_ENCRYPTION_LOCK_PATH,
KEYRING_SYSTEM,
NODE,
NODE_VARIANTS,
NODES,
PROMPT_FLOW_DIR_NAME,
REFRESH_CONNECTIONS_DIR_LOCK_PATH,
REGISTRY_URI_PREFIX,
REMOTE_URI_PREFIX,
USE_VARIANTS,
VARIANTS,
AzureMLWorkspaceTriad,
CommonYamlFields,
)
from promptflow._sdk._errors import (
DecryptConnectionError,
GenerateFlowMetaJsonError,
GenerateFlowToolsJsonError,
StoreConnectionEncryptionKeyError,
UnsecureConnectionError,
)
from promptflow._sdk._vendor import IgnoreFile, get_ignore_file, get_upload_files_from_folder
from promptflow._utils.context_utils import _change_working_dir, inject_sys_path
from promptflow._utils.dataclass_serializer import serialize
from promptflow._utils.logger_utils import get_cli_sdk_logger
from promptflow._utils.utils import _match_reference
from promptflow._utils.yaml_utils import dump_yaml, load_yaml, load_yaml_string
from promptflow.contracts.tool import ToolType
from promptflow.exceptions import ErrorTarget, UserErrorException
CUSTOMIZED_ENCRYPTION_KEY_IN_KEY_RING = None
def use_customized_encryption_key(encryption_key: str):
global CUSTOMIZED_ENCRYPTION_KEY_IN_KEY_RING
CUSTOMIZED_ENCRYPTION_KEY_IN_KEY_RING = encryption_key
yield
CUSTOMIZED_ENCRYPTION_KEY_IN_KEY_RING = None | null |
4,079 | import collections
import datetime
import hashlib
import json
import multiprocessing
import os
import platform
import re
import shutil
import stat
import sys
import tempfile
import uuid
import zipfile
from contextlib import contextmanager
from enum import Enum
from functools import partial
from os import PathLike
from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Tuple, Union
from urllib.parse import urlparse
import keyring
import pydash
from cryptography.fernet import Fernet
from filelock import FileLock
from jinja2 import Template
from keyring.errors import NoKeyringError
from marshmallow import ValidationError
import promptflow
from promptflow._constants import EXTENSION_UA, PF_NO_INTERACTIVE_LOGIN, PF_USER_AGENT, USER_AGENT
from promptflow._sdk._constants import (
AZURE_WORKSPACE_REGEX_FORMAT,
DAG_FILE_NAME,
DEFAULT_ENCODING,
FLOW_META_JSON,
FLOW_META_JSON_GEN_TIMEOUT,
FLOW_TOOLS_JSON,
FLOW_TOOLS_JSON_GEN_TIMEOUT,
HOME_PROMPT_FLOW_DIR,
KEYRING_ENCRYPTION_KEY_NAME,
KEYRING_ENCRYPTION_LOCK_PATH,
KEYRING_SYSTEM,
NODE,
NODE_VARIANTS,
NODES,
PROMPT_FLOW_DIR_NAME,
REFRESH_CONNECTIONS_DIR_LOCK_PATH,
REGISTRY_URI_PREFIX,
REMOTE_URI_PREFIX,
USE_VARIANTS,
VARIANTS,
AzureMLWorkspaceTriad,
CommonYamlFields,
)
from promptflow._sdk._errors import (
DecryptConnectionError,
GenerateFlowMetaJsonError,
GenerateFlowToolsJsonError,
StoreConnectionEncryptionKeyError,
UnsecureConnectionError,
)
from promptflow._sdk._vendor import IgnoreFile, get_ignore_file, get_upload_files_from_folder
from promptflow._utils.context_utils import _change_working_dir, inject_sys_path
from promptflow._utils.dataclass_serializer import serialize
from promptflow._utils.logger_utils import get_cli_sdk_logger
from promptflow._utils.utils import _match_reference
from promptflow._utils.yaml_utils import dump_yaml, load_yaml, load_yaml_string
from promptflow.contracts.tool import ToolType
from promptflow.exceptions import ErrorTarget, UserErrorException
def set_encryption_key(encryption_key: Union[str, bytes]):
if isinstance(encryption_key, bytes):
encryption_key = encryption_key.decode("utf-8")
keyring.set_password("promptflow", "encryption_key", encryption_key) | null |
4,080 | import collections
import datetime
import hashlib
import json
import multiprocessing
import os
import platform
import re
import shutil
import stat
import sys
import tempfile
import uuid
import zipfile
from contextlib import contextmanager
from enum import Enum
from functools import partial
from os import PathLike
from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Tuple, Union
from urllib.parse import urlparse
import keyring
import pydash
from cryptography.fernet import Fernet
from filelock import FileLock
from jinja2 import Template
from keyring.errors import NoKeyringError
from marshmallow import ValidationError
import promptflow
from promptflow._constants import EXTENSION_UA, PF_NO_INTERACTIVE_LOGIN, PF_USER_AGENT, USER_AGENT
from promptflow._sdk._constants import (
AZURE_WORKSPACE_REGEX_FORMAT,
DAG_FILE_NAME,
DEFAULT_ENCODING,
FLOW_META_JSON,
FLOW_META_JSON_GEN_TIMEOUT,
FLOW_TOOLS_JSON,
FLOW_TOOLS_JSON_GEN_TIMEOUT,
HOME_PROMPT_FLOW_DIR,
KEYRING_ENCRYPTION_KEY_NAME,
KEYRING_ENCRYPTION_LOCK_PATH,
KEYRING_SYSTEM,
NODE,
NODE_VARIANTS,
NODES,
PROMPT_FLOW_DIR_NAME,
REFRESH_CONNECTIONS_DIR_LOCK_PATH,
REGISTRY_URI_PREFIX,
REMOTE_URI_PREFIX,
USE_VARIANTS,
VARIANTS,
AzureMLWorkspaceTriad,
CommonYamlFields,
)
from promptflow._sdk._errors import (
DecryptConnectionError,
GenerateFlowMetaJsonError,
GenerateFlowToolsJsonError,
StoreConnectionEncryptionKeyError,
UnsecureConnectionError,
)
from promptflow._sdk._vendor import IgnoreFile, get_ignore_file, get_upload_files_from_folder
from promptflow._utils.context_utils import _change_working_dir, inject_sys_path
from promptflow._utils.dataclass_serializer import serialize
from promptflow._utils.logger_utils import get_cli_sdk_logger
from promptflow._utils.utils import _match_reference
from promptflow._utils.yaml_utils import dump_yaml, load_yaml, load_yaml_string
from promptflow.contracts.tool import ToolType
from promptflow.exceptions import ErrorTarget, UserErrorException
def get_encryption_key(generate_if_not_found: bool = False) -> str:
global CUSTOMIZED_ENCRYPTION_KEY_IN_KEY_RING
global ENCRYPTION_KEY_IN_KEY_RING
if CUSTOMIZED_ENCRYPTION_KEY_IN_KEY_RING is not None:
return CUSTOMIZED_ENCRYPTION_KEY_IN_KEY_RING
if ENCRYPTION_KEY_IN_KEY_RING is not None:
return ENCRYPTION_KEY_IN_KEY_RING
def _get_from_keyring():
try:
# Cache encryption key as mac will pop window to ask for permission when calling get_password
return keyring.get_password(KEYRING_SYSTEM, KEYRING_ENCRYPTION_KEY_NAME)
except NoKeyringError as e:
raise StoreConnectionEncryptionKeyError(
"System keyring backend service not found in your operating system. "
"See https://pypi.org/project/keyring/ to install requirement for different operating system, "
"or 'pip install keyrings.alt' to use the third-party backend. Reach more detail about this error at "
"https://microsoft.github.io/promptflow/how-to-guides/faq.html#connection-creation-failed-with-storeconnectionencryptionkeyerror" # noqa: E501
) from e
ENCRYPTION_KEY_IN_KEY_RING = _get_from_keyring()
if ENCRYPTION_KEY_IN_KEY_RING is not None or not generate_if_not_found:
return ENCRYPTION_KEY_IN_KEY_RING
_encryption_key_lock.acquire()
# Note: we access the keyring twice, as global var can't share across processes.
ENCRYPTION_KEY_IN_KEY_RING = _get_from_keyring()
if ENCRYPTION_KEY_IN_KEY_RING is not None:
return ENCRYPTION_KEY_IN_KEY_RING
try:
ENCRYPTION_KEY_IN_KEY_RING = Fernet.generate_key().decode("utf-8")
keyring.set_password(KEYRING_SYSTEM, KEYRING_ENCRYPTION_KEY_NAME, ENCRYPTION_KEY_IN_KEY_RING)
finally:
_encryption_key_lock.release()
return ENCRYPTION_KEY_IN_KEY_RING
def encrypt_secret_value(secret_value):
encryption_key = get_encryption_key(generate_if_not_found=True)
fernet_client = Fernet(encryption_key)
token = fernet_client.encrypt(secret_value.encode("utf-8"))
return token.decode("utf-8") | null |
4,081 | import collections
import datetime
import hashlib
import json
import multiprocessing
import os
import platform
import re
import shutil
import stat
import sys
import tempfile
import uuid
import zipfile
from contextlib import contextmanager
from enum import Enum
from functools import partial
from os import PathLike
from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Tuple, Union
from urllib.parse import urlparse
import keyring
import pydash
from cryptography.fernet import Fernet
from filelock import FileLock
from jinja2 import Template
from keyring.errors import NoKeyringError
from marshmallow import ValidationError
import promptflow
from promptflow._constants import EXTENSION_UA, PF_NO_INTERACTIVE_LOGIN, PF_USER_AGENT, USER_AGENT
from promptflow._sdk._constants import (
AZURE_WORKSPACE_REGEX_FORMAT,
DAG_FILE_NAME,
DEFAULT_ENCODING,
FLOW_META_JSON,
FLOW_META_JSON_GEN_TIMEOUT,
FLOW_TOOLS_JSON,
FLOW_TOOLS_JSON_GEN_TIMEOUT,
HOME_PROMPT_FLOW_DIR,
KEYRING_ENCRYPTION_KEY_NAME,
KEYRING_ENCRYPTION_LOCK_PATH,
KEYRING_SYSTEM,
NODE,
NODE_VARIANTS,
NODES,
PROMPT_FLOW_DIR_NAME,
REFRESH_CONNECTIONS_DIR_LOCK_PATH,
REGISTRY_URI_PREFIX,
REMOTE_URI_PREFIX,
USE_VARIANTS,
VARIANTS,
AzureMLWorkspaceTriad,
CommonYamlFields,
)
from promptflow._sdk._errors import (
DecryptConnectionError,
GenerateFlowMetaJsonError,
GenerateFlowToolsJsonError,
StoreConnectionEncryptionKeyError,
UnsecureConnectionError,
)
from promptflow._sdk._vendor import IgnoreFile, get_ignore_file, get_upload_files_from_folder
from promptflow._utils.context_utils import _change_working_dir, inject_sys_path
from promptflow._utils.dataclass_serializer import serialize
from promptflow._utils.logger_utils import get_cli_sdk_logger
from promptflow._utils.utils import _match_reference
from promptflow._utils.yaml_utils import dump_yaml, load_yaml, load_yaml_string
from promptflow.contracts.tool import ToolType
from promptflow.exceptions import ErrorTarget, UserErrorException
def get_encryption_key(generate_if_not_found: bool = False) -> str:
def decrypt_secret_value(connection_name, encrypted_secret_value):
encryption_key = get_encryption_key()
if encryption_key is None:
raise Exception("Encryption key not found in keyring.")
fernet_client = Fernet(encryption_key)
try:
return fernet_client.decrypt(encrypted_secret_value.encode("utf-8")).decode("utf-8")
except Exception as e:
if len(encrypted_secret_value) < 57:
# This is to workaround old custom secrets that are not encrypted with Fernet.
# Fernet token: https://github.com/fernet/spec/blob/master/Spec.md
# Format: Version ‖ Timestamp ‖ IV ‖ Ciphertext ‖ HMAC
# Version: 8 bits, Timestamp: 64 bits, IV: 128 bits, HMAC: 256 bits,
# Ciphertext variable length, multiple of 128 bits
# So the minimum length of a Fernet token is 57 bytes
raise UnsecureConnectionError(
f"Please delete and re-create connection {connection_name} "
f"due to a security issue in the old sdk version."
)
raise DecryptConnectionError(
f"Decrypt connection {connection_name} secret failed: {str(e)}. "
f"If you have ever changed your encryption key manually, "
f"please revert it back to the original one, or delete all connections and re-create them."
) | null |
4,082 | import collections
import datetime
import hashlib
import json
import multiprocessing
import os
import platform
import re
import shutil
import stat
import sys
import tempfile
import uuid
import zipfile
from contextlib import contextmanager
from enum import Enum
from functools import partial
from os import PathLike
from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Tuple, Union
from urllib.parse import urlparse
import keyring
import pydash
from cryptography.fernet import Fernet
from filelock import FileLock
from jinja2 import Template
from keyring.errors import NoKeyringError
from marshmallow import ValidationError
import promptflow
from promptflow._constants import EXTENSION_UA, PF_NO_INTERACTIVE_LOGIN, PF_USER_AGENT, USER_AGENT
from promptflow._sdk._constants import (
AZURE_WORKSPACE_REGEX_FORMAT,
DAG_FILE_NAME,
DEFAULT_ENCODING,
FLOW_META_JSON,
FLOW_META_JSON_GEN_TIMEOUT,
FLOW_TOOLS_JSON,
FLOW_TOOLS_JSON_GEN_TIMEOUT,
HOME_PROMPT_FLOW_DIR,
KEYRING_ENCRYPTION_KEY_NAME,
KEYRING_ENCRYPTION_LOCK_PATH,
KEYRING_SYSTEM,
NODE,
NODE_VARIANTS,
NODES,
PROMPT_FLOW_DIR_NAME,
REFRESH_CONNECTIONS_DIR_LOCK_PATH,
REGISTRY_URI_PREFIX,
REMOTE_URI_PREFIX,
USE_VARIANTS,
VARIANTS,
AzureMLWorkspaceTriad,
CommonYamlFields,
)
from promptflow._sdk._errors import (
DecryptConnectionError,
GenerateFlowMetaJsonError,
GenerateFlowToolsJsonError,
StoreConnectionEncryptionKeyError,
UnsecureConnectionError,
)
from promptflow._sdk._vendor import IgnoreFile, get_ignore_file, get_upload_files_from_folder
from promptflow._utils.context_utils import _change_working_dir, inject_sys_path
from promptflow._utils.dataclass_serializer import serialize
from promptflow._utils.logger_utils import get_cli_sdk_logger
from promptflow._utils.utils import _match_reference
from promptflow._utils.yaml_utils import dump_yaml, load_yaml, load_yaml_string
from promptflow.contracts.tool import ToolType
from promptflow.exceptions import ErrorTarget, UserErrorException
def decorate_validation_error(schema: Any, pretty_error: str, additional_message: str = "") -> str:
return f"Validation for {schema.__name__} failed:\n\n {pretty_error} \n\n {additional_message}"
def load_from_dict(schema: Any, data: Dict, context: Dict, additional_message: str = "", **kwargs):
try:
return schema(context=context).load(data, **kwargs)
except ValidationError as e:
pretty_error = json.dumps(e.normalized_messages(), indent=2)
raise ValidationError(decorate_validation_error(schema, pretty_error, additional_message)) | null |
4,083 | import collections
import datetime
import hashlib
import json
import multiprocessing
import os
import platform
import re
import shutil
import stat
import sys
import tempfile
import uuid
import zipfile
from contextlib import contextmanager
from enum import Enum
from functools import partial
from os import PathLike
from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Tuple, Union
from urllib.parse import urlparse
import keyring
import pydash
from cryptography.fernet import Fernet
from filelock import FileLock
from jinja2 import Template
from keyring.errors import NoKeyringError
from marshmallow import ValidationError
import promptflow
from promptflow._constants import EXTENSION_UA, PF_NO_INTERACTIVE_LOGIN, PF_USER_AGENT, USER_AGENT
from promptflow._sdk._constants import (
AZURE_WORKSPACE_REGEX_FORMAT,
DAG_FILE_NAME,
DEFAULT_ENCODING,
FLOW_META_JSON,
FLOW_META_JSON_GEN_TIMEOUT,
FLOW_TOOLS_JSON,
FLOW_TOOLS_JSON_GEN_TIMEOUT,
HOME_PROMPT_FLOW_DIR,
KEYRING_ENCRYPTION_KEY_NAME,
KEYRING_ENCRYPTION_LOCK_PATH,
KEYRING_SYSTEM,
NODE,
NODE_VARIANTS,
NODES,
PROMPT_FLOW_DIR_NAME,
REFRESH_CONNECTIONS_DIR_LOCK_PATH,
REGISTRY_URI_PREFIX,
REMOTE_URI_PREFIX,
USE_VARIANTS,
VARIANTS,
AzureMLWorkspaceTriad,
CommonYamlFields,
)
from promptflow._sdk._errors import (
DecryptConnectionError,
GenerateFlowMetaJsonError,
GenerateFlowToolsJsonError,
StoreConnectionEncryptionKeyError,
UnsecureConnectionError,
)
from promptflow._sdk._vendor import IgnoreFile, get_ignore_file, get_upload_files_from_folder
from promptflow._utils.context_utils import _change_working_dir, inject_sys_path
from promptflow._utils.dataclass_serializer import serialize
from promptflow._utils.logger_utils import get_cli_sdk_logger
from promptflow._utils.utils import _match_reference
from promptflow._utils.yaml_utils import dump_yaml, load_yaml, load_yaml_string
from promptflow.contracts.tool import ToolType
from promptflow.exceptions import ErrorTarget, UserErrorException
def strip_quotation(value):
"""
To avoid escaping chars in command args, args will be surrounded in quotas.
Need to remove the pair of quotation first.
"""
if value.startswith('"') and value.endswith('"'):
return value[1:-1]
elif value.startswith("'") and value.endswith("'"):
return value[1:-1]
else:
return value
def parse_variant(variant: str) -> Tuple[str, str]:
variant_regex = r"\${([^.]+).([^}]+)}"
match = re.match(variant_regex, strip_quotation(variant))
if match:
return match.group(1), match.group(2)
else:
error = ValueError(
f"Invalid variant format: {variant}, variant should be in format of ${{TUNING_NODE.VARIANT}}"
)
raise UserErrorException(
target=ErrorTarget.CONTROL_PLANE_SDK,
message=str(error),
error=error,
) | null |
4,084 | import collections
import datetime
import hashlib
import json
import multiprocessing
import os
import platform
import re
import shutil
import stat
import sys
import tempfile
import uuid
import zipfile
from contextlib import contextmanager
from enum import Enum
from functools import partial
from os import PathLike
from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Tuple, Union
from urllib.parse import urlparse
import keyring
import pydash
from cryptography.fernet import Fernet
from filelock import FileLock
from jinja2 import Template
from keyring.errors import NoKeyringError
from marshmallow import ValidationError
import promptflow
from promptflow._constants import EXTENSION_UA, PF_NO_INTERACTIVE_LOGIN, PF_USER_AGENT, USER_AGENT
from promptflow._sdk._constants import (
AZURE_WORKSPACE_REGEX_FORMAT,
DAG_FILE_NAME,
DEFAULT_ENCODING,
FLOW_META_JSON,
FLOW_META_JSON_GEN_TIMEOUT,
FLOW_TOOLS_JSON,
FLOW_TOOLS_JSON_GEN_TIMEOUT,
HOME_PROMPT_FLOW_DIR,
KEYRING_ENCRYPTION_KEY_NAME,
KEYRING_ENCRYPTION_LOCK_PATH,
KEYRING_SYSTEM,
NODE,
NODE_VARIANTS,
NODES,
PROMPT_FLOW_DIR_NAME,
REFRESH_CONNECTIONS_DIR_LOCK_PATH,
REGISTRY_URI_PREFIX,
REMOTE_URI_PREFIX,
USE_VARIANTS,
VARIANTS,
AzureMLWorkspaceTriad,
CommonYamlFields,
)
from promptflow._sdk._errors import (
DecryptConnectionError,
GenerateFlowMetaJsonError,
GenerateFlowToolsJsonError,
StoreConnectionEncryptionKeyError,
UnsecureConnectionError,
)
from promptflow._sdk._vendor import IgnoreFile, get_ignore_file, get_upload_files_from_folder
from promptflow._utils.context_utils import _change_working_dir, inject_sys_path
from promptflow._utils.dataclass_serializer import serialize
from promptflow._utils.logger_utils import get_cli_sdk_logger
from promptflow._utils.utils import _match_reference
from promptflow._utils.yaml_utils import dump_yaml, load_yaml, load_yaml_string
from promptflow.contracts.tool import ToolType
from promptflow.exceptions import ErrorTarget, UserErrorException
def get_used_connection_names_from_dict(connection_dict: dict):
connection_names = set()
for key, val in connection_dict.items():
connection_name, _ = _match_reference(val)
if connection_name:
connection_names.add(connection_name)
return connection_names
The provided code snippet includes necessary dependencies for implementing the `get_used_connection_names_from_environment_variables` function. Write a Python function `def get_used_connection_names_from_environment_variables()` to solve the following problem:
The function will get all potential related connection names from current environment variables. for example, if part of env var is { "ENV_VAR_1": "${my_connection.key}", "ENV_VAR_2": "${my_connection.key2}", "ENV_VAR_3": "${my_connection2.key}", } The function will return {"my_connection", "my_connection2"}.
Here is the function:
def get_used_connection_names_from_environment_variables():
"""The function will get all potential related connection names from current environment variables.
for example, if part of env var is
{
"ENV_VAR_1": "${my_connection.key}",
"ENV_VAR_2": "${my_connection.key2}",
"ENV_VAR_3": "${my_connection2.key}",
}
The function will return {"my_connection", "my_connection2"}.
"""
return get_used_connection_names_from_dict(os.environ) | The function will get all potential related connection names from current environment variables. for example, if part of env var is { "ENV_VAR_1": "${my_connection.key}", "ENV_VAR_2": "${my_connection.key2}", "ENV_VAR_3": "${my_connection2.key}", } The function will return {"my_connection", "my_connection2"}. |
4,085 | import collections
import datetime
import hashlib
import json
import multiprocessing
import os
import platform
import re
import shutil
import stat
import sys
import tempfile
import uuid
import zipfile
from contextlib import contextmanager
from enum import Enum
from functools import partial
from os import PathLike
from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Tuple, Union
from urllib.parse import urlparse
import keyring
import pydash
from cryptography.fernet import Fernet
from filelock import FileLock
from jinja2 import Template
from keyring.errors import NoKeyringError
from marshmallow import ValidationError
import promptflow
from promptflow._constants import EXTENSION_UA, PF_NO_INTERACTIVE_LOGIN, PF_USER_AGENT, USER_AGENT
from promptflow._sdk._constants import (
AZURE_WORKSPACE_REGEX_FORMAT,
DAG_FILE_NAME,
DEFAULT_ENCODING,
FLOW_META_JSON,
FLOW_META_JSON_GEN_TIMEOUT,
FLOW_TOOLS_JSON,
FLOW_TOOLS_JSON_GEN_TIMEOUT,
HOME_PROMPT_FLOW_DIR,
KEYRING_ENCRYPTION_KEY_NAME,
KEYRING_ENCRYPTION_LOCK_PATH,
KEYRING_SYSTEM,
NODE,
NODE_VARIANTS,
NODES,
PROMPT_FLOW_DIR_NAME,
REFRESH_CONNECTIONS_DIR_LOCK_PATH,
REGISTRY_URI_PREFIX,
REMOTE_URI_PREFIX,
USE_VARIANTS,
VARIANTS,
AzureMLWorkspaceTriad,
CommonYamlFields,
)
from promptflow._sdk._errors import (
DecryptConnectionError,
GenerateFlowMetaJsonError,
GenerateFlowToolsJsonError,
StoreConnectionEncryptionKeyError,
UnsecureConnectionError,
)
from promptflow._sdk._vendor import IgnoreFile, get_ignore_file, get_upload_files_from_folder
from promptflow._utils.context_utils import _change_working_dir, inject_sys_path
from promptflow._utils.dataclass_serializer import serialize
from promptflow._utils.logger_utils import get_cli_sdk_logger
from promptflow._utils.utils import _match_reference
from promptflow._utils.yaml_utils import dump_yaml, load_yaml, load_yaml_string
from promptflow.contracts.tool import ToolType
from promptflow.exceptions import ErrorTarget, UserErrorException
def update_dict_value_with_connections(built_connections, connection_dict: dict):
for key, val in connection_dict.items():
connection_name, connection_key = _match_reference(val)
if connection_name is None:
continue
if connection_name not in built_connections:
continue
if connection_key not in built_connections[connection_name]["value"]:
continue
connection_dict[key] = built_connections[connection_name]["value"][connection_key]
The provided code snippet includes necessary dependencies for implementing the `update_environment_variables_with_connections` function. Write a Python function `def update_environment_variables_with_connections(built_connections)` to solve the following problem:
The function will result env var value ${my_connection.key} to the real connection keys.
Here is the function:
def update_environment_variables_with_connections(built_connections):
"""The function will result env var value ${my_connection.key} to the real connection keys."""
return update_dict_value_with_connections(built_connections, os.environ) | The function will result env var value ${my_connection.key} to the real connection keys. |
4,086 | import collections
import datetime
import hashlib
import json
import multiprocessing
import os
import platform
import re
import shutil
import stat
import sys
import tempfile
import uuid
import zipfile
from contextlib import contextmanager
from enum import Enum
from functools import partial
from os import PathLike
from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Tuple, Union
from urllib.parse import urlparse
import keyring
import pydash
from cryptography.fernet import Fernet
from filelock import FileLock
from jinja2 import Template
from keyring.errors import NoKeyringError
from marshmallow import ValidationError
import promptflow
from promptflow._constants import EXTENSION_UA, PF_NO_INTERACTIVE_LOGIN, PF_USER_AGENT, USER_AGENT
from promptflow._sdk._constants import (
AZURE_WORKSPACE_REGEX_FORMAT,
DAG_FILE_NAME,
DEFAULT_ENCODING,
FLOW_META_JSON,
FLOW_META_JSON_GEN_TIMEOUT,
FLOW_TOOLS_JSON,
FLOW_TOOLS_JSON_GEN_TIMEOUT,
HOME_PROMPT_FLOW_DIR,
KEYRING_ENCRYPTION_KEY_NAME,
KEYRING_ENCRYPTION_LOCK_PATH,
KEYRING_SYSTEM,
NODE,
NODE_VARIANTS,
NODES,
PROMPT_FLOW_DIR_NAME,
REFRESH_CONNECTIONS_DIR_LOCK_PATH,
REGISTRY_URI_PREFIX,
REMOTE_URI_PREFIX,
USE_VARIANTS,
VARIANTS,
AzureMLWorkspaceTriad,
CommonYamlFields,
)
from promptflow._sdk._errors import (
DecryptConnectionError,
GenerateFlowMetaJsonError,
GenerateFlowToolsJsonError,
StoreConnectionEncryptionKeyError,
UnsecureConnectionError,
)
from promptflow._sdk._vendor import IgnoreFile, get_ignore_file, get_upload_files_from_folder
from promptflow._utils.context_utils import _change_working_dir, inject_sys_path
from promptflow._utils.dataclass_serializer import serialize
from promptflow._utils.logger_utils import get_cli_sdk_logger
from promptflow._utils.utils import _match_reference
from promptflow._utils.yaml_utils import dump_yaml, load_yaml, load_yaml_string
from promptflow.contracts.tool import ToolType
from promptflow.exceptions import ErrorTarget, UserErrorException
logger = get_cli_sdk_logger()
The provided code snippet includes necessary dependencies for implementing the `override_connection_config_with_environment_variable` function. Write a Python function `def override_connection_config_with_environment_variable(connections: Dict[str, dict])` to solve the following problem:
The function will use relevant environment variable to override connection configurations. For instance, if there is a custom connection named 'custom_connection' with a configuration key called 'chat_deployment_name,' the function will attempt to retrieve 'chat_deployment_name' from the environment variable 'CUSTOM_CONNECTION_CHAT_DEPLOYMENT_NAME' by default. If the environment variable is not set, it will use the original value as a fallback.
Here is the function:
def override_connection_config_with_environment_variable(connections: Dict[str, dict]):
"""
The function will use relevant environment variable to override connection configurations. For instance, if there
is a custom connection named 'custom_connection' with a configuration key called 'chat_deployment_name,' the
function will attempt to retrieve 'chat_deployment_name' from the environment variable
'CUSTOM_CONNECTION_CHAT_DEPLOYMENT_NAME' by default. If the environment variable is not set, it will use the
original value as a fallback.
"""
for connection_name, connection in connections.items():
values = connection.get("value", {})
for key, val in values.items():
connection_name = connection_name.replace(" ", "_")
env_name = f"{connection_name}_{key}".upper()
if env_name not in os.environ:
continue
values[key] = os.environ[env_name]
logger.info(f"Connection {connection_name}'s {key} is overridden with environment variable {env_name}")
return connections | The function will use relevant environment variable to override connection configurations. For instance, if there is a custom connection named 'custom_connection' with a configuration key called 'chat_deployment_name,' the function will attempt to retrieve 'chat_deployment_name' from the environment variable 'CUSTOM_CONNECTION_CHAT_DEPLOYMENT_NAME' by default. If the environment variable is not set, it will use the original value as a fallback. |
4,087 | import collections
import datetime
import hashlib
import json
import multiprocessing
import os
import platform
import re
import shutil
import stat
import sys
import tempfile
import uuid
import zipfile
from contextlib import contextmanager
from enum import Enum
from functools import partial
from os import PathLike
from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Tuple, Union
from urllib.parse import urlparse
import keyring
import pydash
from cryptography.fernet import Fernet
from filelock import FileLock
from jinja2 import Template
from keyring.errors import NoKeyringError
from marshmallow import ValidationError
import promptflow
from promptflow._constants import EXTENSION_UA, PF_NO_INTERACTIVE_LOGIN, PF_USER_AGENT, USER_AGENT
from promptflow._sdk._constants import (
AZURE_WORKSPACE_REGEX_FORMAT,
DAG_FILE_NAME,
DEFAULT_ENCODING,
FLOW_META_JSON,
FLOW_META_JSON_GEN_TIMEOUT,
FLOW_TOOLS_JSON,
FLOW_TOOLS_JSON_GEN_TIMEOUT,
HOME_PROMPT_FLOW_DIR,
KEYRING_ENCRYPTION_KEY_NAME,
KEYRING_ENCRYPTION_LOCK_PATH,
KEYRING_SYSTEM,
NODE,
NODE_VARIANTS,
NODES,
PROMPT_FLOW_DIR_NAME,
REFRESH_CONNECTIONS_DIR_LOCK_PATH,
REGISTRY_URI_PREFIX,
REMOTE_URI_PREFIX,
USE_VARIANTS,
VARIANTS,
AzureMLWorkspaceTriad,
CommonYamlFields,
)
from promptflow._sdk._errors import (
DecryptConnectionError,
GenerateFlowMetaJsonError,
GenerateFlowToolsJsonError,
StoreConnectionEncryptionKeyError,
UnsecureConnectionError,
)
from promptflow._sdk._vendor import IgnoreFile, get_ignore_file, get_upload_files_from_folder
from promptflow._utils.context_utils import _change_working_dir, inject_sys_path
from promptflow._utils.dataclass_serializer import serialize
from promptflow._utils.logger_utils import get_cli_sdk_logger
from promptflow._utils.utils import _match_reference
from promptflow._utils.yaml_utils import dump_yaml, load_yaml, load_yaml_string
from promptflow.contracts.tool import ToolType
from promptflow.exceptions import ErrorTarget, UserErrorException
def _match_env_reference(val: str):
try:
val = val.strip()
m = re.match(r"^\$\{env:(.+)}$", val)
if not m:
return None
name = m.groups()[0]
return name
except Exception:
# for exceptions when val is not a string, return
return None
The provided code snippet includes necessary dependencies for implementing the `resolve_connections_environment_variable_reference` function. Write a Python function `def resolve_connections_environment_variable_reference(connections: Dict[str, dict])` to solve the following problem:
The function will resolve connection secrets env var reference like api_key: ${env:KEY}
Here is the function:
def resolve_connections_environment_variable_reference(connections: Dict[str, dict]):
"""The function will resolve connection secrets env var reference like api_key: ${env:KEY}"""
for connection in connections.values():
values = connection.get("value", {})
for key, val in values.items():
if not _match_env_reference(val):
continue
env_name = _match_env_reference(val)
if env_name not in os.environ:
raise UserErrorException(f"Environment variable {env_name} is not found.")
values[key] = os.environ[env_name]
return connections | The function will resolve connection secrets env var reference like api_key: ${env:KEY} |
4,088 | import collections
import datetime
import hashlib
import json
import multiprocessing
import os
import platform
import re
import shutil
import stat
import sys
import tempfile
import uuid
import zipfile
from contextlib import contextmanager
from enum import Enum
from functools import partial
from os import PathLike
from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Tuple, Union
from urllib.parse import urlparse
import keyring
import pydash
from cryptography.fernet import Fernet
from filelock import FileLock
from jinja2 import Template
from keyring.errors import NoKeyringError
from marshmallow import ValidationError
import promptflow
from promptflow._constants import EXTENSION_UA, PF_NO_INTERACTIVE_LOGIN, PF_USER_AGENT, USER_AGENT
from promptflow._sdk._constants import (
AZURE_WORKSPACE_REGEX_FORMAT,
DAG_FILE_NAME,
DEFAULT_ENCODING,
FLOW_META_JSON,
FLOW_META_JSON_GEN_TIMEOUT,
FLOW_TOOLS_JSON,
FLOW_TOOLS_JSON_GEN_TIMEOUT,
HOME_PROMPT_FLOW_DIR,
KEYRING_ENCRYPTION_KEY_NAME,
KEYRING_ENCRYPTION_LOCK_PATH,
KEYRING_SYSTEM,
NODE,
NODE_VARIANTS,
NODES,
PROMPT_FLOW_DIR_NAME,
REFRESH_CONNECTIONS_DIR_LOCK_PATH,
REGISTRY_URI_PREFIX,
REMOTE_URI_PREFIX,
USE_VARIANTS,
VARIANTS,
AzureMLWorkspaceTriad,
CommonYamlFields,
)
from promptflow._sdk._errors import (
DecryptConnectionError,
GenerateFlowMetaJsonError,
GenerateFlowToolsJsonError,
StoreConnectionEncryptionKeyError,
UnsecureConnectionError,
)
from promptflow._sdk._vendor import IgnoreFile, get_ignore_file, get_upload_files_from_folder
from promptflow._utils.context_utils import _change_working_dir, inject_sys_path
from promptflow._utils.dataclass_serializer import serialize
from promptflow._utils.logger_utils import get_cli_sdk_logger
from promptflow._utils.utils import _match_reference
from promptflow._utils.yaml_utils import dump_yaml, load_yaml, load_yaml_string
from promptflow.contracts.tool import ToolType
from promptflow.exceptions import ErrorTarget, UserErrorException
def print_red_error(message):
from colorama import Fore, init
init(autoreset=True)
print(Fore.RED + message) | null |
4,089 | import collections
import datetime
import hashlib
import json
import multiprocessing
import os
import platform
import re
import shutil
import stat
import sys
import tempfile
import uuid
import zipfile
from contextlib import contextmanager
from enum import Enum
from functools import partial
from os import PathLike
from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Tuple, Union
from urllib.parse import urlparse
import keyring
import pydash
from cryptography.fernet import Fernet
from filelock import FileLock
from jinja2 import Template
from keyring.errors import NoKeyringError
from marshmallow import ValidationError
import promptflow
from promptflow._constants import EXTENSION_UA, PF_NO_INTERACTIVE_LOGIN, PF_USER_AGENT, USER_AGENT
from promptflow._sdk._constants import (
AZURE_WORKSPACE_REGEX_FORMAT,
DAG_FILE_NAME,
DEFAULT_ENCODING,
FLOW_META_JSON,
FLOW_META_JSON_GEN_TIMEOUT,
FLOW_TOOLS_JSON,
FLOW_TOOLS_JSON_GEN_TIMEOUT,
HOME_PROMPT_FLOW_DIR,
KEYRING_ENCRYPTION_KEY_NAME,
KEYRING_ENCRYPTION_LOCK_PATH,
KEYRING_SYSTEM,
NODE,
NODE_VARIANTS,
NODES,
PROMPT_FLOW_DIR_NAME,
REFRESH_CONNECTIONS_DIR_LOCK_PATH,
REGISTRY_URI_PREFIX,
REMOTE_URI_PREFIX,
USE_VARIANTS,
VARIANTS,
AzureMLWorkspaceTriad,
CommonYamlFields,
)
from promptflow._sdk._errors import (
DecryptConnectionError,
GenerateFlowMetaJsonError,
GenerateFlowToolsJsonError,
StoreConnectionEncryptionKeyError,
UnsecureConnectionError,
)
from promptflow._sdk._vendor import IgnoreFile, get_ignore_file, get_upload_files_from_folder
from promptflow._utils.context_utils import _change_working_dir, inject_sys_path
from promptflow._utils.dataclass_serializer import serialize
from promptflow._utils.logger_utils import get_cli_sdk_logger
from promptflow._utils.utils import _match_reference
from promptflow._utils.yaml_utils import dump_yaml, load_yaml, load_yaml_string
from promptflow.contracts.tool import ToolType
from promptflow.exceptions import ErrorTarget, UserErrorException
def print_yellow_warning(message):
from colorama import Fore, init
init(autoreset=True)
print(Fore.YELLOW + message)
def safe_parse_object_list(obj_list, parser, message_generator):
results = []
for obj in obj_list:
try:
results.append(parser(obj))
except Exception as e:
extended_message = f"{message_generator(obj)} Error: {type(e).__name__}, {str(e)}"
print_yellow_warning(extended_message)
return results | null |
4,090 | import collections
import datetime
import hashlib
import json
import multiprocessing
import os
import platform
import re
import shutil
import stat
import sys
import tempfile
import uuid
import zipfile
from contextlib import contextmanager
from enum import Enum
from functools import partial
from os import PathLike
from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Tuple, Union
from urllib.parse import urlparse
import keyring
import pydash
from cryptography.fernet import Fernet
from filelock import FileLock
from jinja2 import Template
from keyring.errors import NoKeyringError
from marshmallow import ValidationError
import promptflow
from promptflow._constants import EXTENSION_UA, PF_NO_INTERACTIVE_LOGIN, PF_USER_AGENT, USER_AGENT
from promptflow._sdk._constants import (
AZURE_WORKSPACE_REGEX_FORMAT,
DAG_FILE_NAME,
DEFAULT_ENCODING,
FLOW_META_JSON,
FLOW_META_JSON_GEN_TIMEOUT,
FLOW_TOOLS_JSON,
FLOW_TOOLS_JSON_GEN_TIMEOUT,
HOME_PROMPT_FLOW_DIR,
KEYRING_ENCRYPTION_KEY_NAME,
KEYRING_ENCRYPTION_LOCK_PATH,
KEYRING_SYSTEM,
NODE,
NODE_VARIANTS,
NODES,
PROMPT_FLOW_DIR_NAME,
REFRESH_CONNECTIONS_DIR_LOCK_PATH,
REGISTRY_URI_PREFIX,
REMOTE_URI_PREFIX,
USE_VARIANTS,
VARIANTS,
AzureMLWorkspaceTriad,
CommonYamlFields,
)
from promptflow._sdk._errors import (
DecryptConnectionError,
GenerateFlowMetaJsonError,
GenerateFlowToolsJsonError,
StoreConnectionEncryptionKeyError,
UnsecureConnectionError,
)
from promptflow._sdk._vendor import IgnoreFile, get_ignore_file, get_upload_files_from_folder
from promptflow._utils.context_utils import _change_working_dir, inject_sys_path
from promptflow._utils.dataclass_serializer import serialize
from promptflow._utils.logger_utils import get_cli_sdk_logger
from promptflow._utils.utils import _match_reference
from promptflow._utils.yaml_utils import dump_yaml, load_yaml, load_yaml_string
from promptflow.contracts.tool import ToolType
from promptflow.exceptions import ErrorTarget, UserErrorException
def _sanitize_python_variable_name(name: str):
from promptflow._utils.utils import _sanitize_python_variable_name
return _sanitize_python_variable_name(name) | null |
4,091 | import collections
import datetime
import hashlib
import json
import multiprocessing
import os
import platform
import re
import shutil
import stat
import sys
import tempfile
import uuid
import zipfile
from contextlib import contextmanager
from enum import Enum
from functools import partial
from os import PathLike
from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Tuple, Union
from urllib.parse import urlparse
import keyring
import pydash
from cryptography.fernet import Fernet
from filelock import FileLock
from jinja2 import Template
from keyring.errors import NoKeyringError
from marshmallow import ValidationError
import promptflow
from promptflow._constants import EXTENSION_UA, PF_NO_INTERACTIVE_LOGIN, PF_USER_AGENT, USER_AGENT
from promptflow._sdk._constants import (
AZURE_WORKSPACE_REGEX_FORMAT,
DAG_FILE_NAME,
DEFAULT_ENCODING,
FLOW_META_JSON,
FLOW_META_JSON_GEN_TIMEOUT,
FLOW_TOOLS_JSON,
FLOW_TOOLS_JSON_GEN_TIMEOUT,
HOME_PROMPT_FLOW_DIR,
KEYRING_ENCRYPTION_KEY_NAME,
KEYRING_ENCRYPTION_LOCK_PATH,
KEYRING_SYSTEM,
NODE,
NODE_VARIANTS,
NODES,
PROMPT_FLOW_DIR_NAME,
REFRESH_CONNECTIONS_DIR_LOCK_PATH,
REGISTRY_URI_PREFIX,
REMOTE_URI_PREFIX,
USE_VARIANTS,
VARIANTS,
AzureMLWorkspaceTriad,
CommonYamlFields,
)
from promptflow._sdk._errors import (
DecryptConnectionError,
GenerateFlowMetaJsonError,
GenerateFlowToolsJsonError,
StoreConnectionEncryptionKeyError,
UnsecureConnectionError,
)
from promptflow._sdk._vendor import IgnoreFile, get_ignore_file, get_upload_files_from_folder
from promptflow._utils.context_utils import _change_working_dir, inject_sys_path
from promptflow._utils.dataclass_serializer import serialize
from promptflow._utils.logger_utils import get_cli_sdk_logger
from promptflow._utils.utils import _match_reference
from promptflow._utils.yaml_utils import dump_yaml, load_yaml, load_yaml_string
from promptflow.contracts.tool import ToolType
from promptflow.exceptions import ErrorTarget, UserErrorException
logger = get_cli_sdk_logger()
def _get_additional_includes(yaml_path):
flow_dag = load_yaml(yaml_path)
return flow_dag.get("additional_includes", [])
def _is_folder_to_compress(path: Path) -> bool:
"""Check if the additional include needs to compress corresponding folder as a zip.
For example, given additional include /mnt/c/hello.zip
1) if a file named /mnt/c/hello.zip already exists, return False (simply copy)
2) if a folder named /mnt/c/hello exists, return True (compress as a zip and copy)
:param path: Given path in additional include.
:type path: Path
:return: If the path need to be compressed as a zip file.
:rtype: bool
"""
if path.suffix != ".zip":
return False
# if zip file exists, simply copy as other additional includes
if path.exists():
return False
# remove .zip suffix and check whether the folder exists
stem_path = path.parent / path.stem
return stem_path.is_dir()
def _resolve_folder_to_compress(base_path: Path, include: str, dst_path: Path) -> None:
"""resolve the zip additional include, need to compress corresponding folder."""
zip_additional_include = (base_path / include).resolve()
folder_to_zip = zip_additional_include.parent / zip_additional_include.stem
zip_file = dst_path / zip_additional_include.name
with zipfile.ZipFile(zip_file, "w") as zf:
zf.write(folder_to_zip, os.path.relpath(folder_to_zip, folder_to_zip.parent)) # write root in zip
for root, _, files in os.walk(folder_to_zip, followlinks=True):
for file in files:
file_path = os.path.join(folder_to_zip, file)
zf.write(file_path, os.path.relpath(file_path, folder_to_zip.parent))
def _merge_local_code_and_additional_includes(code_path: Path):
# TODO: unify variable names: flow_dir_path, flow_dag_path, flow_path
def additional_includes_copy(src, relative_path, target_dir):
if src.is_file():
dst = Path(target_dir) / relative_path
dst.parent.mkdir(parents=True, exist_ok=True)
if dst.exists():
logger.warning(
"Found duplicate file in additional includes, "
f"additional include file {src} will overwrite {relative_path}"
)
shutil.copy2(src, dst)
else:
for name in src.glob("*"):
additional_includes_copy(name, Path(relative_path) / name.name, target_dir)
if code_path.is_dir():
yaml_path = (Path(code_path) / DAG_FILE_NAME).resolve()
code_path = code_path.resolve()
else:
yaml_path = code_path.resolve()
code_path = code_path.parent.resolve()
with tempfile.TemporaryDirectory() as temp_dir:
shutil.copytree(code_path.resolve().as_posix(), temp_dir, dirs_exist_ok=True)
for item in _get_additional_includes(yaml_path):
src_path = Path(item)
if not src_path.is_absolute():
src_path = (code_path / item).resolve()
if _is_folder_to_compress(src_path):
_resolve_folder_to_compress(code_path, item, Path(temp_dir))
# early continue as the folder is compressed as a zip file
continue
if not src_path.exists():
error = ValueError(f"Unable to find additional include {item}")
raise UserErrorException(
target=ErrorTarget.CONTROL_PLANE_SDK,
message=str(error),
error=error,
)
additional_includes_copy(src_path, relative_path=src_path.name, target_dir=temp_dir)
yield temp_dir | null |
4,092 | import collections
import datetime
import hashlib
import json
import multiprocessing
import os
import platform
import re
import shutil
import stat
import sys
import tempfile
import uuid
import zipfile
from contextlib import contextmanager
from enum import Enum
from functools import partial
from os import PathLike
from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Tuple, Union
from urllib.parse import urlparse
import keyring
import pydash
from cryptography.fernet import Fernet
from filelock import FileLock
from jinja2 import Template
from keyring.errors import NoKeyringError
from marshmallow import ValidationError
import promptflow
from promptflow._constants import EXTENSION_UA, PF_NO_INTERACTIVE_LOGIN, PF_USER_AGENT, USER_AGENT
from promptflow._sdk._constants import (
AZURE_WORKSPACE_REGEX_FORMAT,
DAG_FILE_NAME,
DEFAULT_ENCODING,
FLOW_META_JSON,
FLOW_META_JSON_GEN_TIMEOUT,
FLOW_TOOLS_JSON,
FLOW_TOOLS_JSON_GEN_TIMEOUT,
HOME_PROMPT_FLOW_DIR,
KEYRING_ENCRYPTION_KEY_NAME,
KEYRING_ENCRYPTION_LOCK_PATH,
KEYRING_SYSTEM,
NODE,
NODE_VARIANTS,
NODES,
PROMPT_FLOW_DIR_NAME,
REFRESH_CONNECTIONS_DIR_LOCK_PATH,
REGISTRY_URI_PREFIX,
REMOTE_URI_PREFIX,
USE_VARIANTS,
VARIANTS,
AzureMLWorkspaceTriad,
CommonYamlFields,
)
from promptflow._sdk._errors import (
DecryptConnectionError,
GenerateFlowMetaJsonError,
GenerateFlowToolsJsonError,
StoreConnectionEncryptionKeyError,
UnsecureConnectionError,
)
from promptflow._sdk._vendor import IgnoreFile, get_ignore_file, get_upload_files_from_folder
from promptflow._utils.context_utils import _change_working_dir, inject_sys_path
from promptflow._utils.dataclass_serializer import serialize
from promptflow._utils.logger_utils import get_cli_sdk_logger
from promptflow._utils.utils import _match_reference
from promptflow._utils.yaml_utils import dump_yaml, load_yaml, load_yaml_string
from promptflow.contracts.tool import ToolType
from promptflow.exceptions import ErrorTarget, UserErrorException
def incremental_print(log: str, printed: int, fileout) -> int:
count = 0
for line in log.splitlines():
if count >= printed:
fileout.write(line + "\n")
printed += 1
count += 1
return printed | null |
4,093 | import collections
import datetime
import hashlib
import json
import multiprocessing
import os
import platform
import re
import shutil
import stat
import sys
import tempfile
import uuid
import zipfile
from contextlib import contextmanager
from enum import Enum
from functools import partial
from os import PathLike
from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Tuple, Union
from urllib.parse import urlparse
import keyring
import pydash
from cryptography.fernet import Fernet
from filelock import FileLock
from jinja2 import Template
from keyring.errors import NoKeyringError
from marshmallow import ValidationError
import promptflow
from promptflow._constants import EXTENSION_UA, PF_NO_INTERACTIVE_LOGIN, PF_USER_AGENT, USER_AGENT
from promptflow._sdk._constants import (
AZURE_WORKSPACE_REGEX_FORMAT,
DAG_FILE_NAME,
DEFAULT_ENCODING,
FLOW_META_JSON,
FLOW_META_JSON_GEN_TIMEOUT,
FLOW_TOOLS_JSON,
FLOW_TOOLS_JSON_GEN_TIMEOUT,
HOME_PROMPT_FLOW_DIR,
KEYRING_ENCRYPTION_KEY_NAME,
KEYRING_ENCRYPTION_LOCK_PATH,
KEYRING_SYSTEM,
NODE,
NODE_VARIANTS,
NODES,
PROMPT_FLOW_DIR_NAME,
REFRESH_CONNECTIONS_DIR_LOCK_PATH,
REGISTRY_URI_PREFIX,
REMOTE_URI_PREFIX,
USE_VARIANTS,
VARIANTS,
AzureMLWorkspaceTriad,
CommonYamlFields,
)
from promptflow._sdk._errors import (
DecryptConnectionError,
GenerateFlowMetaJsonError,
GenerateFlowToolsJsonError,
StoreConnectionEncryptionKeyError,
UnsecureConnectionError,
)
from promptflow._sdk._vendor import IgnoreFile, get_ignore_file, get_upload_files_from_folder
from promptflow._utils.context_utils import _change_working_dir, inject_sys_path
from promptflow._utils.dataclass_serializer import serialize
from promptflow._utils.logger_utils import get_cli_sdk_logger
from promptflow._utils.utils import _match_reference
from promptflow._utils.yaml_utils import dump_yaml, load_yaml, load_yaml_string
from promptflow.contracts.tool import ToolType
from promptflow.exceptions import ErrorTarget, UserErrorException
def get_promptflow_sdk_version() -> str:
try:
return promptflow.__version__
except AttributeError:
# if promptflow is installed from source, it does not have __version__ attribute
return "0.0.1"
def print_pf_version():
print("promptflow\t\t\t {}".format(get_promptflow_sdk_version()))
print()
print("Executable '{}'".format(os.path.abspath(sys.executable)))
print("Python ({}) {}".format(platform.system(), sys.version)) | null |
4,094 | import collections
import datetime
import hashlib
import json
import multiprocessing
import os
import platform
import re
import shutil
import stat
import sys
import tempfile
import uuid
import zipfile
from contextlib import contextmanager
from enum import Enum
from functools import partial
from os import PathLike
from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Tuple, Union
from urllib.parse import urlparse
import keyring
import pydash
from cryptography.fernet import Fernet
from filelock import FileLock
from jinja2 import Template
from keyring.errors import NoKeyringError
from marshmallow import ValidationError
import promptflow
from promptflow._constants import EXTENSION_UA, PF_NO_INTERACTIVE_LOGIN, PF_USER_AGENT, USER_AGENT
from promptflow._sdk._constants import (
AZURE_WORKSPACE_REGEX_FORMAT,
DAG_FILE_NAME,
DEFAULT_ENCODING,
FLOW_META_JSON,
FLOW_META_JSON_GEN_TIMEOUT,
FLOW_TOOLS_JSON,
FLOW_TOOLS_JSON_GEN_TIMEOUT,
HOME_PROMPT_FLOW_DIR,
KEYRING_ENCRYPTION_KEY_NAME,
KEYRING_ENCRYPTION_LOCK_PATH,
KEYRING_SYSTEM,
NODE,
NODE_VARIANTS,
NODES,
PROMPT_FLOW_DIR_NAME,
REFRESH_CONNECTIONS_DIR_LOCK_PATH,
REGISTRY_URI_PREFIX,
REMOTE_URI_PREFIX,
USE_VARIANTS,
VARIANTS,
AzureMLWorkspaceTriad,
CommonYamlFields,
)
from promptflow._sdk._errors import (
DecryptConnectionError,
GenerateFlowMetaJsonError,
GenerateFlowToolsJsonError,
StoreConnectionEncryptionKeyError,
UnsecureConnectionError,
)
from promptflow._sdk._vendor import IgnoreFile, get_ignore_file, get_upload_files_from_folder
from promptflow._utils.context_utils import _change_working_dir, inject_sys_path
from promptflow._utils.dataclass_serializer import serialize
from promptflow._utils.logger_utils import get_cli_sdk_logger
from promptflow._utils.utils import _match_reference
from promptflow._utils.yaml_utils import dump_yaml, load_yaml, load_yaml_string
from promptflow.contracts.tool import ToolType
from promptflow.exceptions import ErrorTarget, UserErrorException
The provided code snippet includes necessary dependencies for implementing the `_retrieve_tool_func_result` function. Write a Python function `def _retrieve_tool_func_result(func_call_scenario: str, function_config: Dict)` to solve the following problem:
Retrieve tool func result according to func_call_scenario. :param func_call_scenario: function call scenario :param function_config: function config in tool meta. Should contain'func_path' and 'func_kwargs'. :return: func call result according to func_call_scenario.
Here is the function:
def _retrieve_tool_func_result(func_call_scenario: str, function_config: Dict):
"""Retrieve tool func result according to func_call_scenario.
:param func_call_scenario: function call scenario
:param function_config: function config in tool meta. Should contain'func_path' and 'func_kwargs'.
:return: func call result according to func_call_scenario.
"""
from promptflow._core.tools_manager import retrieve_tool_func_result
func_path = function_config.get("func_path", "")
func_kwargs = function_config.get("func_kwargs", {})
# May call azure control plane api in the custom function to list Azure resources.
# which may need Azure workspace triple.
# TODO: move this method to a common place.
from promptflow._cli._utils import get_workspace_triad_from_local
workspace_triad = get_workspace_triad_from_local()
if workspace_triad.subscription_id and workspace_triad.resource_group_name and workspace_triad.workspace_name:
result = retrieve_tool_func_result(func_call_scenario, func_path, func_kwargs, workspace_triad._asdict())
# if no workspace triple available, just skip.
else:
result = retrieve_tool_func_result(func_call_scenario, func_path, func_kwargs)
result_with_log = {"result": result, "logs": {}}
return result_with_log | Retrieve tool func result according to func_call_scenario. :param func_call_scenario: function call scenario :param function_config: function config in tool meta. Should contain'func_path' and 'func_kwargs'. :return: func call result according to func_call_scenario. |
4,095 | import collections
import datetime
import hashlib
import json
import multiprocessing
import os
import platform
import re
import shutil
import stat
import sys
import tempfile
import uuid
import zipfile
from contextlib import contextmanager
from enum import Enum
from functools import partial
from os import PathLike
from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Tuple, Union
from urllib.parse import urlparse
import keyring
import pydash
from cryptography.fernet import Fernet
from filelock import FileLock
from jinja2 import Template
from keyring.errors import NoKeyringError
from marshmallow import ValidationError
import promptflow
from promptflow._constants import EXTENSION_UA, PF_NO_INTERACTIVE_LOGIN, PF_USER_AGENT, USER_AGENT
from promptflow._sdk._constants import (
AZURE_WORKSPACE_REGEX_FORMAT,
DAG_FILE_NAME,
DEFAULT_ENCODING,
FLOW_META_JSON,
FLOW_META_JSON_GEN_TIMEOUT,
FLOW_TOOLS_JSON,
FLOW_TOOLS_JSON_GEN_TIMEOUT,
HOME_PROMPT_FLOW_DIR,
KEYRING_ENCRYPTION_KEY_NAME,
KEYRING_ENCRYPTION_LOCK_PATH,
KEYRING_SYSTEM,
NODE,
NODE_VARIANTS,
NODES,
PROMPT_FLOW_DIR_NAME,
REFRESH_CONNECTIONS_DIR_LOCK_PATH,
REGISTRY_URI_PREFIX,
REMOTE_URI_PREFIX,
USE_VARIANTS,
VARIANTS,
AzureMLWorkspaceTriad,
CommonYamlFields,
)
from promptflow._sdk._errors import (
DecryptConnectionError,
GenerateFlowMetaJsonError,
GenerateFlowToolsJsonError,
StoreConnectionEncryptionKeyError,
UnsecureConnectionError,
)
from promptflow._sdk._vendor import IgnoreFile, get_ignore_file, get_upload_files_from_folder
from promptflow._utils.context_utils import _change_working_dir, inject_sys_path
from promptflow._utils.dataclass_serializer import serialize
from promptflow._utils.logger_utils import get_cli_sdk_logger
from promptflow._utils.utils import _match_reference
from promptflow._utils.yaml_utils import dump_yaml, load_yaml, load_yaml_string
from promptflow.contracts.tool import ToolType
from promptflow.exceptions import ErrorTarget, UserErrorException
The provided code snippet includes necessary dependencies for implementing the `_gen_dynamic_list` function. Write a Python function `def _gen_dynamic_list(function_config: Dict) -> List` to solve the following problem:
Generate dynamic list for a tool input. :param function_config: function config in tool meta. Should contain'func_path' and 'func_kwargs'. :return: a list of tool input dynamic enums.
Here is the function:
def _gen_dynamic_list(function_config: Dict) -> List:
"""Generate dynamic list for a tool input.
:param function_config: function config in tool meta. Should contain'func_path' and 'func_kwargs'.
:return: a list of tool input dynamic enums.
"""
from promptflow._core.tools_manager import gen_dynamic_list
func_path = function_config.get("func_path", "")
func_kwargs = function_config.get("func_kwargs", {})
# May call azure control plane api in the custom function to list Azure resources.
# which may need Azure workspace triple.
# TODO: move this method to a common place.
from promptflow._cli._utils import get_workspace_triad_from_local
workspace_triad = get_workspace_triad_from_local()
if workspace_triad.subscription_id and workspace_triad.resource_group_name and workspace_triad.workspace_name:
return gen_dynamic_list(func_path, func_kwargs, workspace_triad._asdict())
# if no workspace triple available, just skip.
else:
return gen_dynamic_list(func_path, func_kwargs) | Generate dynamic list for a tool input. :param function_config: function config in tool meta. Should contain'func_path' and 'func_kwargs'. :return: a list of tool input dynamic enums. |
4,096 | import collections
import datetime
import hashlib
import json
import multiprocessing
import os
import platform
import re
import shutil
import stat
import sys
import tempfile
import uuid
import zipfile
from contextlib import contextmanager
from enum import Enum
from functools import partial
from os import PathLike
from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Tuple, Union
from urllib.parse import urlparse
import keyring
import pydash
from cryptography.fernet import Fernet
from filelock import FileLock
from jinja2 import Template
from keyring.errors import NoKeyringError
from marshmallow import ValidationError
import promptflow
from promptflow._constants import EXTENSION_UA, PF_NO_INTERACTIVE_LOGIN, PF_USER_AGENT, USER_AGENT
from promptflow._sdk._constants import (
AZURE_WORKSPACE_REGEX_FORMAT,
DAG_FILE_NAME,
DEFAULT_ENCODING,
FLOW_META_JSON,
FLOW_META_JSON_GEN_TIMEOUT,
FLOW_TOOLS_JSON,
FLOW_TOOLS_JSON_GEN_TIMEOUT,
HOME_PROMPT_FLOW_DIR,
KEYRING_ENCRYPTION_KEY_NAME,
KEYRING_ENCRYPTION_LOCK_PATH,
KEYRING_SYSTEM,
NODE,
NODE_VARIANTS,
NODES,
PROMPT_FLOW_DIR_NAME,
REFRESH_CONNECTIONS_DIR_LOCK_PATH,
REGISTRY_URI_PREFIX,
REMOTE_URI_PREFIX,
USE_VARIANTS,
VARIANTS,
AzureMLWorkspaceTriad,
CommonYamlFields,
)
from promptflow._sdk._errors import (
DecryptConnectionError,
GenerateFlowMetaJsonError,
GenerateFlowToolsJsonError,
StoreConnectionEncryptionKeyError,
UnsecureConnectionError,
)
from promptflow._sdk._vendor import IgnoreFile, get_ignore_file, get_upload_files_from_folder
from promptflow._utils.context_utils import _change_working_dir, inject_sys_path
from promptflow._utils.dataclass_serializer import serialize
from promptflow._utils.logger_utils import get_cli_sdk_logger
from promptflow._utils.utils import _match_reference
from promptflow._utils.yaml_utils import dump_yaml, load_yaml, load_yaml_string
from promptflow.contracts.tool import ToolType
from promptflow.exceptions import ErrorTarget, UserErrorException
def _generate_tool_meta(
flow_directory: Path,
tools: List[Tuple[str, str]],
raise_error: bool,
timeout: int,
*,
include_errors_in_output: bool = False,
load_in_subprocess: bool = True,
) -> Dict[str, dict]:
"""Generate tool meta from files.
:param flow_directory: flow directory
:param tools: tool list
:param raise_error: whether raise error when generate meta failed
:param timeout: timeout for generate meta
:param include_errors_in_output: whether include errors in output
:param load_in_subprocess: whether load tool meta with subprocess to prevent system path disturb. Default is True.
If set to False, will load tool meta in sync mode and timeout need to be handled outside current process.
:return: tool meta dict
"""
from promptflow._core.tool_meta_generator import generate_tool_meta, generate_tool_meta_in_subprocess
tools = _construct_tool_dict(tools)
if load_in_subprocess:
# use multiprocess generate to avoid system path disturb
tool_dict, exception_dict = generate_tool_meta_in_subprocess(flow_directory, tools, logger, timeout=timeout)
else:
# There is no built-in method to forcefully stop a running thread/coroutine in Python
# because abruptly stopping a thread can cause issues like resource leaks,
# deadlocks, or inconsistent states.
# Caller needs to handle the timeout outside current process.
logger.warning(
"Generate meta in current process and timeout won't take effect. "
"Please handle timeout manually outside current process."
)
tool_dict, exception_dict = generate_tool_meta(flow_directory, tools)
res = {source: tool for source, tool in tool_dict.items()}
for source in res:
# remove name in tool meta
res[source].pop("name")
# convert string Enum to string
if isinstance(res[source]["type"], Enum):
res[source]["type"] = res[source]["type"].value
# not all tools have inputs, so check first
if "inputs" in res[source]:
for tool_input in res[source]["inputs"]:
tool_input_type = res[source]["inputs"][tool_input]["type"]
for i in range(len(tool_input_type)):
if isinstance(tool_input_type[i], Enum):
tool_input_type[i] = tool_input_type[i].value
# collect errors and print warnings, exception_dict is a dict of source and error dict
errors = {source: error_dict.get("message", "unknown exception") for source, error_dict in exception_dict.items()}
for source in errors:
if include_errors_in_output:
res[source] = errors[source]
else:
logger.warning(f"Generate meta for source {source!r} failed: {errors[source]}.")
if raise_error and len(errors) > 0:
error_message = "Generate meta failed, detail error(s):\n" + json.dumps(errors, indent=4)
raise GenerateFlowToolsJsonError(error_message)
return res
def _generate_package_tools(keys: Optional[List[str]] = None) -> dict:
from promptflow._core.tools_manager import collect_package_tools
return collect_package_tools(keys=keys)
def _get_involved_code_and_package(
data: dict,
) -> Tuple[List[Tuple[str, str]], Set[str], Dict[str, List[str]]]:
tools = [] # List[Tuple[source_file, tool_type]]
used_packages = set()
source_path_mapping = collections.defaultdict(list)
for node_i, node in enumerate(data[NODES]):
_update_involved_tools_and_packages(
node,
f"{NODES}.{node_i}",
tools=tools,
used_packages=used_packages,
source_path_mapping=source_path_mapping,
)
# understand DAG to parse variants
# TODO: should we allow source to appear both in node and node variants?
if node.get(USE_VARIANTS) is True:
node_variants = data[NODE_VARIANTS][node["name"]]
for variant_id in node_variants[VARIANTS]:
node_with_variant = node_variants[VARIANTS][variant_id][NODE]
_update_involved_tools_and_packages(
node_with_variant,
f"{NODE_VARIANTS}.{node['name']}.{VARIANTS}.{variant_id}.{NODE}",
tools=tools,
used_packages=used_packages,
source_path_mapping=source_path_mapping,
)
if None in used_packages:
used_packages.remove(None)
return tools, used_packages, source_path_mapping
The provided code snippet includes necessary dependencies for implementing the `generate_flow_tools_json` function. Write a Python function `def generate_flow_tools_json( flow_directory: Union[str, Path], dump: bool = True, raise_error: bool = True, timeout: int = FLOW_TOOLS_JSON_GEN_TIMEOUT, *, include_errors_in_output: bool = False, target_source: str = None, used_packages_only: bool = False, source_path_mapping: Dict[str, List[str]] = None, ) -> dict` to solve the following problem:
Generate flow.tools.json for a flow directory. :param flow_directory: path to flow directory. :param dump: whether to dump to .promptflow/flow.tools.json, default value is True. :param raise_error: whether to raise the error, default value is True. :param timeout: timeout for generation, default value is 60 seconds. :param include_errors_in_output: whether to include error messages in output, default value is False. :param target_source: the source name to filter result, default value is None. Note that we will update system path in coroutine if target_source is provided given it's expected to be from a specific cli call. :param used_packages_only: whether to only include used packages, default value is False. :param source_path_mapping: if specified, record yaml paths for each source.
Here is the function:
def generate_flow_tools_json(
flow_directory: Union[str, Path],
dump: bool = True,
raise_error: bool = True,
timeout: int = FLOW_TOOLS_JSON_GEN_TIMEOUT,
*,
include_errors_in_output: bool = False,
target_source: str = None,
used_packages_only: bool = False,
source_path_mapping: Dict[str, List[str]] = None,
) -> dict:
"""Generate flow.tools.json for a flow directory.
:param flow_directory: path to flow directory.
:param dump: whether to dump to .promptflow/flow.tools.json, default value is True.
:param raise_error: whether to raise the error, default value is True.
:param timeout: timeout for generation, default value is 60 seconds.
:param include_errors_in_output: whether to include error messages in output, default value is False.
:param target_source: the source name to filter result, default value is None. Note that we will update system path
in coroutine if target_source is provided given it's expected to be from a specific cli call.
:param used_packages_only: whether to only include used packages, default value is False.
:param source_path_mapping: if specified, record yaml paths for each source.
"""
flow_directory = Path(flow_directory).resolve()
# parse flow DAG
data = load_yaml(flow_directory / DAG_FILE_NAME)
tools, used_packages, _source_path_mapping = _get_involved_code_and_package(data)
# update passed in source_path_mapping if specified
if source_path_mapping is not None:
source_path_mapping.update(_source_path_mapping)
# filter tools by target_source if specified
if target_source is not None:
tools = list(filter(lambda x: x[0] == target_source, tools))
# generate content
# TODO: remove type in tools (input) and code (output)
flow_tools = {
"code": _generate_tool_meta(
flow_directory,
tools,
raise_error=raise_error,
timeout=timeout,
include_errors_in_output=include_errors_in_output,
# we don't need to protect system path according to the target usage when target_source is specified
load_in_subprocess=target_source is None,
),
# specified source may only appear in code tools
"package": {}
if target_source is not None
else _generate_package_tools(keys=list(used_packages) if used_packages_only else None),
}
if dump:
# dump as flow.tools.json
promptflow_folder = flow_directory / PROMPT_FLOW_DIR_NAME
promptflow_folder.mkdir(exist_ok=True)
with open(promptflow_folder / FLOW_TOOLS_JSON, mode="w", encoding=DEFAULT_ENCODING) as f:
json.dump(flow_tools, f, indent=4)
return flow_tools | Generate flow.tools.json for a flow directory. :param flow_directory: path to flow directory. :param dump: whether to dump to .promptflow/flow.tools.json, default value is True. :param raise_error: whether to raise the error, default value is True. :param timeout: timeout for generation, default value is 60 seconds. :param include_errors_in_output: whether to include error messages in output, default value is False. :param target_source: the source name to filter result, default value is None. Note that we will update system path in coroutine if target_source is provided given it's expected to be from a specific cli call. :param used_packages_only: whether to only include used packages, default value is False. :param source_path_mapping: if specified, record yaml paths for each source. |
4,097 | import collections
import datetime
import hashlib
import json
import multiprocessing
import os
import platform
import re
import shutil
import stat
import sys
import tempfile
import uuid
import zipfile
from contextlib import contextmanager
from enum import Enum
from functools import partial
from os import PathLike
from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Tuple, Union
from urllib.parse import urlparse
import keyring
import pydash
from cryptography.fernet import Fernet
from filelock import FileLock
from jinja2 import Template
from keyring.errors import NoKeyringError
from marshmallow import ValidationError
import promptflow
from promptflow._constants import EXTENSION_UA, PF_NO_INTERACTIVE_LOGIN, PF_USER_AGENT, USER_AGENT
from promptflow._sdk._constants import (
AZURE_WORKSPACE_REGEX_FORMAT,
DAG_FILE_NAME,
DEFAULT_ENCODING,
FLOW_META_JSON,
FLOW_META_JSON_GEN_TIMEOUT,
FLOW_TOOLS_JSON,
FLOW_TOOLS_JSON_GEN_TIMEOUT,
HOME_PROMPT_FLOW_DIR,
KEYRING_ENCRYPTION_KEY_NAME,
KEYRING_ENCRYPTION_LOCK_PATH,
KEYRING_SYSTEM,
NODE,
NODE_VARIANTS,
NODES,
PROMPT_FLOW_DIR_NAME,
REFRESH_CONNECTIONS_DIR_LOCK_PATH,
REGISTRY_URI_PREFIX,
REMOTE_URI_PREFIX,
USE_VARIANTS,
VARIANTS,
AzureMLWorkspaceTriad,
CommonYamlFields,
)
from promptflow._sdk._errors import (
DecryptConnectionError,
GenerateFlowMetaJsonError,
GenerateFlowToolsJsonError,
StoreConnectionEncryptionKeyError,
UnsecureConnectionError,
)
from promptflow._sdk._vendor import IgnoreFile, get_ignore_file, get_upload_files_from_folder
from promptflow._utils.context_utils import _change_working_dir, inject_sys_path
from promptflow._utils.dataclass_serializer import serialize
from promptflow._utils.logger_utils import get_cli_sdk_logger
from promptflow._utils.utils import _match_reference
from promptflow._utils.yaml_utils import dump_yaml, load_yaml, load_yaml_string
from promptflow.contracts.tool import ToolType
from promptflow.exceptions import ErrorTarget, UserErrorException
class ClientUserAgentUtil:
"""SDK/CLI side user agent utilities."""
def _get_context(cls):
from promptflow._core.operation_context import OperationContext
return OperationContext.get_instance()
def get_user_agent(cls):
from promptflow._core.operation_context import OperationContext
context = cls._get_context()
# directly get from context since client side won't need promptflow/xxx.
return context.get(OperationContext.USER_AGENT_KEY, "").strip()
def append_user_agent(cls, user_agent: Optional[str]):
if not user_agent:
return
context = cls._get_context()
context.append_user_agent(user_agent)
def update_user_agent_from_env_var(cls):
# this is for backward compatibility: we should use PF_USER_AGENT in newer versions.
for env_name in [USER_AGENT, PF_USER_AGENT]:
if env_name in os.environ:
cls.append_user_agent(os.environ[env_name])
def update_user_agent_from_config(cls):
"""Update user agent from config. 1p customer will set it. We'll add PFCustomer_ as prefix."""
from promptflow._sdk._configuration import Configuration
config = Configuration.get_instance()
user_agent = config.get_user_agent()
if user_agent:
cls.append_user_agent(user_agent)
The provided code snippet includes necessary dependencies for implementing the `setup_user_agent_to_operation_context` function. Write a Python function `def setup_user_agent_to_operation_context(user_agent)` to solve the following problem:
Setup user agent to OperationContext. For calls from extension, ua will be like: prompt-flow-extension/ promptflow-cli/ promptflow-sdk/ For calls from CLI, ua will be like: promptflow-cli/ promptflow-sdk/ For calls from SDK, ua will be like: promptflow-sdk/ For 1p customer call which set user agent in config, ua will be like: PFCustomer_XXX/
Here is the function:
def setup_user_agent_to_operation_context(user_agent):
"""Setup user agent to OperationContext.
For calls from extension, ua will be like: prompt-flow-extension/ promptflow-cli/ promptflow-sdk/
For calls from CLI, ua will be like: promptflow-cli/ promptflow-sdk/
For calls from SDK, ua will be like: promptflow-sdk/
For 1p customer call which set user agent in config, ua will be like: PFCustomer_XXX/
"""
# add user added UA after SDK/CLI
ClientUserAgentUtil.append_user_agent(user_agent)
ClientUserAgentUtil.update_user_agent_from_env_var()
ClientUserAgentUtil.update_user_agent_from_config()
return ClientUserAgentUtil.get_user_agent() | Setup user agent to OperationContext. For calls from extension, ua will be like: prompt-flow-extension/ promptflow-cli/ promptflow-sdk/ For calls from CLI, ua will be like: promptflow-cli/ promptflow-sdk/ For calls from SDK, ua will be like: promptflow-sdk/ For 1p customer call which set user agent in config, ua will be like: PFCustomer_XXX/ |
4,098 | import collections
import datetime
import hashlib
import json
import multiprocessing
import os
import platform
import re
import shutil
import stat
import sys
import tempfile
import uuid
import zipfile
from contextlib import contextmanager
from enum import Enum
from functools import partial
from os import PathLike
from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Tuple, Union
from urllib.parse import urlparse
import keyring
import pydash
from cryptography.fernet import Fernet
from filelock import FileLock
from jinja2 import Template
from keyring.errors import NoKeyringError
from marshmallow import ValidationError
import promptflow
from promptflow._constants import EXTENSION_UA, PF_NO_INTERACTIVE_LOGIN, PF_USER_AGENT, USER_AGENT
from promptflow._sdk._constants import (
AZURE_WORKSPACE_REGEX_FORMAT,
DAG_FILE_NAME,
DEFAULT_ENCODING,
FLOW_META_JSON,
FLOW_META_JSON_GEN_TIMEOUT,
FLOW_TOOLS_JSON,
FLOW_TOOLS_JSON_GEN_TIMEOUT,
HOME_PROMPT_FLOW_DIR,
KEYRING_ENCRYPTION_KEY_NAME,
KEYRING_ENCRYPTION_LOCK_PATH,
KEYRING_SYSTEM,
NODE,
NODE_VARIANTS,
NODES,
PROMPT_FLOW_DIR_NAME,
REFRESH_CONNECTIONS_DIR_LOCK_PATH,
REGISTRY_URI_PREFIX,
REMOTE_URI_PREFIX,
USE_VARIANTS,
VARIANTS,
AzureMLWorkspaceTriad,
CommonYamlFields,
)
from promptflow._sdk._errors import (
DecryptConnectionError,
GenerateFlowMetaJsonError,
GenerateFlowToolsJsonError,
StoreConnectionEncryptionKeyError,
UnsecureConnectionError,
)
from promptflow._sdk._vendor import IgnoreFile, get_ignore_file, get_upload_files_from_folder
from promptflow._utils.context_utils import _change_working_dir, inject_sys_path
from promptflow._utils.dataclass_serializer import serialize
from promptflow._utils.logger_utils import get_cli_sdk_logger
from promptflow._utils.utils import _match_reference
from promptflow._utils.yaml_utils import dump_yaml, load_yaml, load_yaml_string
from promptflow.contracts.tool import ToolType
from promptflow.exceptions import ErrorTarget, UserErrorException
class ClientUserAgentUtil:
"""SDK/CLI side user agent utilities."""
def _get_context(cls):
from promptflow._core.operation_context import OperationContext
return OperationContext.get_instance()
def get_user_agent(cls):
from promptflow._core.operation_context import OperationContext
context = cls._get_context()
# directly get from context since client side won't need promptflow/xxx.
return context.get(OperationContext.USER_AGENT_KEY, "").strip()
def append_user_agent(cls, user_agent: Optional[str]):
if not user_agent:
return
context = cls._get_context()
context.append_user_agent(user_agent)
def update_user_agent_from_env_var(cls):
# this is for backward compatibility: we should use PF_USER_AGENT in newer versions.
for env_name in [USER_AGENT, PF_USER_AGENT]:
if env_name in os.environ:
cls.append_user_agent(os.environ[env_name])
def update_user_agent_from_config(cls):
"""Update user agent from config. 1p customer will set it. We'll add PFCustomer_ as prefix."""
from promptflow._sdk._configuration import Configuration
config = Configuration.get_instance()
user_agent = config.get_user_agent()
if user_agent:
cls.append_user_agent(user_agent)
The provided code snippet includes necessary dependencies for implementing the `call_from_extension` function. Write a Python function `def call_from_extension() -> bool` to solve the following problem:
Return true if current request is from extension.
Here is the function:
def call_from_extension() -> bool:
"""Return true if current request is from extension."""
ClientUserAgentUtil.update_user_agent_from_env_var()
user_agent = ClientUserAgentUtil.get_user_agent()
return EXTENSION_UA in user_agent | Return true if current request is from extension. |
4,099 | import collections
import datetime
import hashlib
import json
import multiprocessing
import os
import platform
import re
import shutil
import stat
import sys
import tempfile
import uuid
import zipfile
from contextlib import contextmanager
from enum import Enum
from functools import partial
from os import PathLike
from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Tuple, Union
from urllib.parse import urlparse
import keyring
import pydash
from cryptography.fernet import Fernet
from filelock import FileLock
from jinja2 import Template
from keyring.errors import NoKeyringError
from marshmallow import ValidationError
import promptflow
from promptflow._constants import EXTENSION_UA, PF_NO_INTERACTIVE_LOGIN, PF_USER_AGENT, USER_AGENT
from promptflow._sdk._constants import (
AZURE_WORKSPACE_REGEX_FORMAT,
DAG_FILE_NAME,
DEFAULT_ENCODING,
FLOW_META_JSON,
FLOW_META_JSON_GEN_TIMEOUT,
FLOW_TOOLS_JSON,
FLOW_TOOLS_JSON_GEN_TIMEOUT,
HOME_PROMPT_FLOW_DIR,
KEYRING_ENCRYPTION_KEY_NAME,
KEYRING_ENCRYPTION_LOCK_PATH,
KEYRING_SYSTEM,
NODE,
NODE_VARIANTS,
NODES,
PROMPT_FLOW_DIR_NAME,
REFRESH_CONNECTIONS_DIR_LOCK_PATH,
REGISTRY_URI_PREFIX,
REMOTE_URI_PREFIX,
USE_VARIANTS,
VARIANTS,
AzureMLWorkspaceTriad,
CommonYamlFields,
)
from promptflow._sdk._errors import (
DecryptConnectionError,
GenerateFlowMetaJsonError,
GenerateFlowToolsJsonError,
StoreConnectionEncryptionKeyError,
UnsecureConnectionError,
)
from promptflow._sdk._vendor import IgnoreFile, get_ignore_file, get_upload_files_from_folder
from promptflow._utils.context_utils import _change_working_dir, inject_sys_path
from promptflow._utils.dataclass_serializer import serialize
from promptflow._utils.logger_utils import get_cli_sdk_logger
from promptflow._utils.utils import _match_reference
from promptflow._utils.yaml_utils import dump_yaml, load_yaml, load_yaml_string
from promptflow.contracts.tool import ToolType
from promptflow.exceptions import ErrorTarget, UserErrorException
def generate_random_string(length: int = 6) -> str:
import random
import string
return "".join(random.choice(string.ascii_lowercase) for _ in range(length)) | null |
4,100 | import collections
import datetime
import hashlib
import json
import multiprocessing
import os
import platform
import re
import shutil
import stat
import sys
import tempfile
import uuid
import zipfile
from contextlib import contextmanager
from enum import Enum
from functools import partial
from os import PathLike
from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Tuple, Union
from urllib.parse import urlparse
import keyring
import pydash
from cryptography.fernet import Fernet
from filelock import FileLock
from jinja2 import Template
from keyring.errors import NoKeyringError
from marshmallow import ValidationError
import promptflow
from promptflow._constants import EXTENSION_UA, PF_NO_INTERACTIVE_LOGIN, PF_USER_AGENT, USER_AGENT
from promptflow._sdk._constants import (
AZURE_WORKSPACE_REGEX_FORMAT,
DAG_FILE_NAME,
DEFAULT_ENCODING,
FLOW_META_JSON,
FLOW_META_JSON_GEN_TIMEOUT,
FLOW_TOOLS_JSON,
FLOW_TOOLS_JSON_GEN_TIMEOUT,
HOME_PROMPT_FLOW_DIR,
KEYRING_ENCRYPTION_KEY_NAME,
KEYRING_ENCRYPTION_LOCK_PATH,
KEYRING_SYSTEM,
NODE,
NODE_VARIANTS,
NODES,
PROMPT_FLOW_DIR_NAME,
REFRESH_CONNECTIONS_DIR_LOCK_PATH,
REGISTRY_URI_PREFIX,
REMOTE_URI_PREFIX,
USE_VARIANTS,
VARIANTS,
AzureMLWorkspaceTriad,
CommonYamlFields,
)
from promptflow._sdk._errors import (
DecryptConnectionError,
GenerateFlowMetaJsonError,
GenerateFlowToolsJsonError,
StoreConnectionEncryptionKeyError,
UnsecureConnectionError,
)
from promptflow._sdk._vendor import IgnoreFile, get_ignore_file, get_upload_files_from_folder
from promptflow._utils.context_utils import _change_working_dir, inject_sys_path
from promptflow._utils.dataclass_serializer import serialize
from promptflow._utils.logger_utils import get_cli_sdk_logger
from promptflow._utils.utils import _match_reference
from promptflow._utils.yaml_utils import dump_yaml, load_yaml, load_yaml_string
from promptflow.contracts.tool import ToolType
from promptflow.exceptions import ErrorTarget, UserErrorException
def render_jinja_template(template_path, *, trim_blocks=True, keep_trailing_newline=True, **kwargs):
with open(template_path, "r", encoding=DEFAULT_ENCODING) as f:
template = Template(f.read(), trim_blocks=trim_blocks, keep_trailing_newline=keep_trailing_newline)
return template.render(**kwargs)
class PromptflowIgnoreFile(IgnoreFile):
# TODO add more files to this list.
IGNORE_FILE = [".runs", "__pycache__"]
def __init__(self, prompt_flow_path: Union[Path, str]):
super(PromptflowIgnoreFile, self).__init__(prompt_flow_path)
self._path = Path(prompt_flow_path)
self._ignore_tools_json = False
def base_path(self) -> Path:
return self._path
def _get_ignore_list(self):
"""Get ignore list from ignore file contents."""
if not self.exists():
return []
base_ignore = get_ignore_file(self.base_path)
result = self.IGNORE_FILE + base_ignore._get_ignore_list()
if self._ignore_tools_json:
result.append(f"{PROMPT_FLOW_DIR_NAME}/{FLOW_TOOLS_JSON}")
return result
def copy_tree_respect_template_and_ignore_file(source: Path, target: Path, render_context: dict = None):
def is_template(path: str):
return path.endswith(".jinja2")
for source_path, target_path in get_upload_files_from_folder(
path=source,
ignore_file=PromptflowIgnoreFile(prompt_flow_path=source),
):
(target / target_path).parent.mkdir(parents=True, exist_ok=True)
if render_context is None or not is_template(source_path):
shutil.copy(source_path, target / target_path)
else:
(target / target_path[: -len(".jinja2")]).write_bytes(
# always use unix line ending
render_jinja_template(source_path, **render_context)
.encode("utf-8")
.replace(b"\r\n", b"\n"),
) | null |
4,101 | import collections
import datetime
import hashlib
import json
import multiprocessing
import os
import platform
import re
import shutil
import stat
import sys
import tempfile
import uuid
import zipfile
from contextlib import contextmanager
from enum import Enum
from functools import partial
from os import PathLike
from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Tuple, Union
from urllib.parse import urlparse
import keyring
import pydash
from cryptography.fernet import Fernet
from filelock import FileLock
from jinja2 import Template
from keyring.errors import NoKeyringError
from marshmallow import ValidationError
import promptflow
from promptflow._constants import EXTENSION_UA, PF_NO_INTERACTIVE_LOGIN, PF_USER_AGENT, USER_AGENT
from promptflow._sdk._constants import (
AZURE_WORKSPACE_REGEX_FORMAT,
DAG_FILE_NAME,
DEFAULT_ENCODING,
FLOW_META_JSON,
FLOW_META_JSON_GEN_TIMEOUT,
FLOW_TOOLS_JSON,
FLOW_TOOLS_JSON_GEN_TIMEOUT,
HOME_PROMPT_FLOW_DIR,
KEYRING_ENCRYPTION_KEY_NAME,
KEYRING_ENCRYPTION_LOCK_PATH,
KEYRING_SYSTEM,
NODE,
NODE_VARIANTS,
NODES,
PROMPT_FLOW_DIR_NAME,
REFRESH_CONNECTIONS_DIR_LOCK_PATH,
REGISTRY_URI_PREFIX,
REMOTE_URI_PREFIX,
USE_VARIANTS,
VARIANTS,
AzureMLWorkspaceTriad,
CommonYamlFields,
)
from promptflow._sdk._errors import (
DecryptConnectionError,
GenerateFlowMetaJsonError,
GenerateFlowToolsJsonError,
StoreConnectionEncryptionKeyError,
UnsecureConnectionError,
)
from promptflow._sdk._vendor import IgnoreFile, get_ignore_file, get_upload_files_from_folder
from promptflow._utils.context_utils import _change_working_dir, inject_sys_path
from promptflow._utils.dataclass_serializer import serialize
from promptflow._utils.logger_utils import get_cli_sdk_logger
from promptflow._utils.utils import _match_reference
from promptflow._utils.yaml_utils import dump_yaml, load_yaml, load_yaml_string
from promptflow.contracts.tool import ToolType
from promptflow.exceptions import ErrorTarget, UserErrorException
The provided code snippet includes necessary dependencies for implementing the `get_local_connections_from_executable` function. Write a Python function `def get_local_connections_from_executable( executable, client, connections_to_ignore: List[str] = None, connections_to_add: List[str] = None )` to solve the following problem:
Get local connections from executable. executable: The executable flow object. client: Local client to get connections. connections_to_ignore: The connection names to ignore when getting connections. connections_to_add: The connection names to add when getting connections.
Here is the function:
def get_local_connections_from_executable(
executable, client, connections_to_ignore: List[str] = None, connections_to_add: List[str] = None
):
"""Get local connections from executable.
executable: The executable flow object.
client: Local client to get connections.
connections_to_ignore: The connection names to ignore when getting connections.
connections_to_add: The connection names to add when getting connections.
"""
connection_names = executable.get_connection_names()
if connections_to_add:
connection_names.update(connections_to_add)
connections_to_ignore = connections_to_ignore or []
result = {}
for n in connection_names:
if n not in connections_to_ignore:
conn = client.connections.get(name=n, with_secrets=True)
result[n] = conn._to_execution_connection_dict()
return result | Get local connections from executable. executable: The executable flow object. client: Local client to get connections. connections_to_ignore: The connection names to ignore when getting connections. connections_to_add: The connection names to add when getting connections. |
4,102 | import collections
import datetime
import hashlib
import json
import multiprocessing
import os
import platform
import re
import shutil
import stat
import sys
import tempfile
import uuid
import zipfile
from contextlib import contextmanager
from enum import Enum
from functools import partial
from os import PathLike
from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Tuple, Union
from urllib.parse import urlparse
import keyring
import pydash
from cryptography.fernet import Fernet
from filelock import FileLock
from jinja2 import Template
from keyring.errors import NoKeyringError
from marshmallow import ValidationError
import promptflow
from promptflow._constants import EXTENSION_UA, PF_NO_INTERACTIVE_LOGIN, PF_USER_AGENT, USER_AGENT
from promptflow._sdk._constants import (
AZURE_WORKSPACE_REGEX_FORMAT,
DAG_FILE_NAME,
DEFAULT_ENCODING,
FLOW_META_JSON,
FLOW_META_JSON_GEN_TIMEOUT,
FLOW_TOOLS_JSON,
FLOW_TOOLS_JSON_GEN_TIMEOUT,
HOME_PROMPT_FLOW_DIR,
KEYRING_ENCRYPTION_KEY_NAME,
KEYRING_ENCRYPTION_LOCK_PATH,
KEYRING_SYSTEM,
NODE,
NODE_VARIANTS,
NODES,
PROMPT_FLOW_DIR_NAME,
REFRESH_CONNECTIONS_DIR_LOCK_PATH,
REGISTRY_URI_PREFIX,
REMOTE_URI_PREFIX,
USE_VARIANTS,
VARIANTS,
AzureMLWorkspaceTriad,
CommonYamlFields,
)
from promptflow._sdk._errors import (
DecryptConnectionError,
GenerateFlowMetaJsonError,
GenerateFlowToolsJsonError,
StoreConnectionEncryptionKeyError,
UnsecureConnectionError,
)
from promptflow._sdk._vendor import IgnoreFile, get_ignore_file, get_upload_files_from_folder
from promptflow._utils.context_utils import _change_working_dir, inject_sys_path
from promptflow._utils.dataclass_serializer import serialize
from promptflow._utils.logger_utils import get_cli_sdk_logger
from promptflow._utils.utils import _match_reference
from promptflow._utils.yaml_utils import dump_yaml, load_yaml, load_yaml_string
from promptflow.contracts.tool import ToolType
from promptflow.exceptions import ErrorTarget, UserErrorException
def _generate_connections_dir():
_refresh_connection_dir_lock = FileLock(REFRESH_CONNECTIONS_DIR_LOCK_PATH)
def refresh_connections_dir(connection_spec_files, connection_template_yamls):
connections_dir = _generate_connections_dir()
# Use lock to prevent concurrent access
with _refresh_connection_dir_lock:
if os.path.isdir(connections_dir):
shutil.rmtree(connections_dir)
os.makedirs(connections_dir)
if connection_spec_files and connection_template_yamls:
for connection_name, content in connection_spec_files.items():
file_name = connection_name + ".spec.json"
with open(connections_dir / file_name, "w", encoding=DEFAULT_ENCODING) as f:
json.dump(content, f, indent=2)
# use YAML to dump template file in order to keep the comments
for connection_name, content in connection_template_yamls.items():
yaml_data = load_yaml_string(content)
file_name = connection_name + ".template.yaml"
with open(connections_dir / file_name, "w", encoding=DEFAULT_ENCODING) as f:
dump_yaml(yaml_data, f) | null |
4,103 | import collections
import datetime
import hashlib
import json
import multiprocessing
import os
import platform
import re
import shutil
import stat
import sys
import tempfile
import uuid
import zipfile
from contextlib import contextmanager
from enum import Enum
from functools import partial
from os import PathLike
from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Tuple, Union
from urllib.parse import urlparse
import keyring
import pydash
from cryptography.fernet import Fernet
from filelock import FileLock
from jinja2 import Template
from keyring.errors import NoKeyringError
from marshmallow import ValidationError
import promptflow
from promptflow._constants import EXTENSION_UA, PF_NO_INTERACTIVE_LOGIN, PF_USER_AGENT, USER_AGENT
from promptflow._sdk._constants import (
AZURE_WORKSPACE_REGEX_FORMAT,
DAG_FILE_NAME,
DEFAULT_ENCODING,
FLOW_META_JSON,
FLOW_META_JSON_GEN_TIMEOUT,
FLOW_TOOLS_JSON,
FLOW_TOOLS_JSON_GEN_TIMEOUT,
HOME_PROMPT_FLOW_DIR,
KEYRING_ENCRYPTION_KEY_NAME,
KEYRING_ENCRYPTION_LOCK_PATH,
KEYRING_SYSTEM,
NODE,
NODE_VARIANTS,
NODES,
PROMPT_FLOW_DIR_NAME,
REFRESH_CONNECTIONS_DIR_LOCK_PATH,
REGISTRY_URI_PREFIX,
REMOTE_URI_PREFIX,
USE_VARIANTS,
VARIANTS,
AzureMLWorkspaceTriad,
CommonYamlFields,
)
from promptflow._sdk._errors import (
DecryptConnectionError,
GenerateFlowMetaJsonError,
GenerateFlowToolsJsonError,
StoreConnectionEncryptionKeyError,
UnsecureConnectionError,
)
from promptflow._sdk._vendor import IgnoreFile, get_ignore_file, get_upload_files_from_folder
from promptflow._utils.context_utils import _change_working_dir, inject_sys_path
from promptflow._utils.dataclass_serializer import serialize
from promptflow._utils.logger_utils import get_cli_sdk_logger
from promptflow._utils.utils import _match_reference
from promptflow._utils.yaml_utils import dump_yaml, load_yaml, load_yaml_string
from promptflow.contracts.tool import ToolType
from promptflow.exceptions import ErrorTarget, UserErrorException
The provided code snippet includes necessary dependencies for implementing the `dump_flow_result` function. Write a Python function `def dump_flow_result(flow_folder, prefix, flow_result=None, node_result=None, custom_path=None)` to solve the following problem:
Dump flow result for extension. :param flow_folder: The flow folder. :param prefix: The file prefix. :param flow_result: The flow result returned by exec_line. :param node_result: The node result when test node returned by load_and_exec_node. :param custom_path: The custom path to dump flow result.
Here is the function:
def dump_flow_result(flow_folder, prefix, flow_result=None, node_result=None, custom_path=None):
"""Dump flow result for extension.
:param flow_folder: The flow folder.
:param prefix: The file prefix.
:param flow_result: The flow result returned by exec_line.
:param node_result: The node result when test node returned by load_and_exec_node.
:param custom_path: The custom path to dump flow result.
"""
if flow_result:
flow_serialize_result = {
"flow_runs": [serialize(flow_result.run_info)],
"node_runs": [serialize(run) for run in flow_result.node_run_infos.values()],
}
else:
flow_serialize_result = {
"flow_runs": [],
"node_runs": [serialize(node_result)],
}
dump_folder = Path(flow_folder) / PROMPT_FLOW_DIR_NAME if custom_path is None else Path(custom_path)
dump_folder.mkdir(parents=True, exist_ok=True)
with open(dump_folder / f"{prefix}.detail.json", "w", encoding=DEFAULT_ENCODING) as f:
json.dump(flow_serialize_result, f, indent=2, ensure_ascii=False)
if node_result:
metrics = flow_serialize_result["node_runs"][0]["metrics"]
output = flow_serialize_result["node_runs"][0]["output"]
else:
metrics = flow_serialize_result["flow_runs"][0]["metrics"]
output = flow_serialize_result["flow_runs"][0]["output"]
if metrics:
with open(dump_folder / f"{prefix}.metrics.json", "w", encoding=DEFAULT_ENCODING) as f:
json.dump(metrics, f, indent=2, ensure_ascii=False)
if output:
with open(dump_folder / f"{prefix}.output.json", "w", encoding=DEFAULT_ENCODING) as f:
json.dump(output, f, indent=2, ensure_ascii=False) | Dump flow result for extension. :param flow_folder: The flow folder. :param prefix: The file prefix. :param flow_result: The flow result returned by exec_line. :param node_result: The node result when test node returned by load_and_exec_node. :param custom_path: The custom path to dump flow result. |
4,104 | import collections
import datetime
import hashlib
import json
import multiprocessing
import os
import platform
import re
import shutil
import stat
import sys
import tempfile
import uuid
import zipfile
from contextlib import contextmanager
from enum import Enum
from functools import partial
from os import PathLike
from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Tuple, Union
from urllib.parse import urlparse
import keyring
import pydash
from cryptography.fernet import Fernet
from filelock import FileLock
from jinja2 import Template
from keyring.errors import NoKeyringError
from marshmallow import ValidationError
import promptflow
from promptflow._constants import EXTENSION_UA, PF_NO_INTERACTIVE_LOGIN, PF_USER_AGENT, USER_AGENT
from promptflow._sdk._constants import (
AZURE_WORKSPACE_REGEX_FORMAT,
DAG_FILE_NAME,
DEFAULT_ENCODING,
FLOW_META_JSON,
FLOW_META_JSON_GEN_TIMEOUT,
FLOW_TOOLS_JSON,
FLOW_TOOLS_JSON_GEN_TIMEOUT,
HOME_PROMPT_FLOW_DIR,
KEYRING_ENCRYPTION_KEY_NAME,
KEYRING_ENCRYPTION_LOCK_PATH,
KEYRING_SYSTEM,
NODE,
NODE_VARIANTS,
NODES,
PROMPT_FLOW_DIR_NAME,
REFRESH_CONNECTIONS_DIR_LOCK_PATH,
REGISTRY_URI_PREFIX,
REMOTE_URI_PREFIX,
USE_VARIANTS,
VARIANTS,
AzureMLWorkspaceTriad,
CommonYamlFields,
)
from promptflow._sdk._errors import (
DecryptConnectionError,
GenerateFlowMetaJsonError,
GenerateFlowToolsJsonError,
StoreConnectionEncryptionKeyError,
UnsecureConnectionError,
)
from promptflow._sdk._vendor import IgnoreFile, get_ignore_file, get_upload_files_from_folder
from promptflow._utils.context_utils import _change_working_dir, inject_sys_path
from promptflow._utils.dataclass_serializer import serialize
from promptflow._utils.logger_utils import get_cli_sdk_logger
from promptflow._utils.utils import _match_reference
from promptflow._utils.yaml_utils import dump_yaml, load_yaml, load_yaml_string
from promptflow.contracts.tool import ToolType
from promptflow.exceptions import ErrorTarget, UserErrorException
def read_write_by_user():
return stat.S_IRUSR | stat.S_IWUSR | null |
4,105 | import collections
import datetime
import hashlib
import json
import multiprocessing
import os
import platform
import re
import shutil
import stat
import sys
import tempfile
import uuid
import zipfile
from contextlib import contextmanager
from enum import Enum
from functools import partial
from os import PathLike
from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Tuple, Union
from urllib.parse import urlparse
import keyring
import pydash
from cryptography.fernet import Fernet
from filelock import FileLock
from jinja2 import Template
from keyring.errors import NoKeyringError
from marshmallow import ValidationError
import promptflow
from promptflow._constants import EXTENSION_UA, PF_NO_INTERACTIVE_LOGIN, PF_USER_AGENT, USER_AGENT
from promptflow._sdk._constants import (
AZURE_WORKSPACE_REGEX_FORMAT,
DAG_FILE_NAME,
DEFAULT_ENCODING,
FLOW_META_JSON,
FLOW_META_JSON_GEN_TIMEOUT,
FLOW_TOOLS_JSON,
FLOW_TOOLS_JSON_GEN_TIMEOUT,
HOME_PROMPT_FLOW_DIR,
KEYRING_ENCRYPTION_KEY_NAME,
KEYRING_ENCRYPTION_LOCK_PATH,
KEYRING_SYSTEM,
NODE,
NODE_VARIANTS,
NODES,
PROMPT_FLOW_DIR_NAME,
REFRESH_CONNECTIONS_DIR_LOCK_PATH,
REGISTRY_URI_PREFIX,
REMOTE_URI_PREFIX,
USE_VARIANTS,
VARIANTS,
AzureMLWorkspaceTriad,
CommonYamlFields,
)
from promptflow._sdk._errors import (
DecryptConnectionError,
GenerateFlowMetaJsonError,
GenerateFlowToolsJsonError,
StoreConnectionEncryptionKeyError,
UnsecureConnectionError,
)
from promptflow._sdk._vendor import IgnoreFile, get_ignore_file, get_upload_files_from_folder
from promptflow._utils.context_utils import _change_working_dir, inject_sys_path
from promptflow._utils.dataclass_serializer import serialize
from promptflow._utils.logger_utils import get_cli_sdk_logger
from promptflow._utils.utils import _match_reference
from promptflow._utils.yaml_utils import dump_yaml, load_yaml, load_yaml_string
from promptflow.contracts.tool import ToolType
from promptflow.exceptions import ErrorTarget, UserErrorException
The provided code snippet includes necessary dependencies for implementing the `remove_empty_element_from_dict` function. Write a Python function `def remove_empty_element_from_dict(obj: dict) -> dict` to solve the following problem:
Remove empty element from dict, e.g. {"a": 1, "b": {}} -> {"a": 1}
Here is the function:
def remove_empty_element_from_dict(obj: dict) -> dict:
"""Remove empty element from dict, e.g. {"a": 1, "b": {}} -> {"a": 1}"""
new_dict = {}
for key, value in obj.items():
if isinstance(value, dict):
value = remove_empty_element_from_dict(value)
if value is not None:
new_dict[key] = value
return new_dict | Remove empty element from dict, e.g. {"a": 1, "b": {}} -> {"a": 1} |
4,106 | import collections
import datetime
import hashlib
import json
import multiprocessing
import os
import platform
import re
import shutil
import stat
import sys
import tempfile
import uuid
import zipfile
from contextlib import contextmanager
from enum import Enum
from functools import partial
from os import PathLike
from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Tuple, Union
from urllib.parse import urlparse
import keyring
import pydash
from cryptography.fernet import Fernet
from filelock import FileLock
from jinja2 import Template
from keyring.errors import NoKeyringError
from marshmallow import ValidationError
import promptflow
from promptflow._constants import EXTENSION_UA, PF_NO_INTERACTIVE_LOGIN, PF_USER_AGENT, USER_AGENT
from promptflow._sdk._constants import (
AZURE_WORKSPACE_REGEX_FORMAT,
DAG_FILE_NAME,
DEFAULT_ENCODING,
FLOW_META_JSON,
FLOW_META_JSON_GEN_TIMEOUT,
FLOW_TOOLS_JSON,
FLOW_TOOLS_JSON_GEN_TIMEOUT,
HOME_PROMPT_FLOW_DIR,
KEYRING_ENCRYPTION_KEY_NAME,
KEYRING_ENCRYPTION_LOCK_PATH,
KEYRING_SYSTEM,
NODE,
NODE_VARIANTS,
NODES,
PROMPT_FLOW_DIR_NAME,
REFRESH_CONNECTIONS_DIR_LOCK_PATH,
REGISTRY_URI_PREFIX,
REMOTE_URI_PREFIX,
USE_VARIANTS,
VARIANTS,
AzureMLWorkspaceTriad,
CommonYamlFields,
)
from promptflow._sdk._errors import (
DecryptConnectionError,
GenerateFlowMetaJsonError,
GenerateFlowToolsJsonError,
StoreConnectionEncryptionKeyError,
UnsecureConnectionError,
)
from promptflow._sdk._vendor import IgnoreFile, get_ignore_file, get_upload_files_from_folder
from promptflow._utils.context_utils import _change_working_dir, inject_sys_path
from promptflow._utils.dataclass_serializer import serialize
from promptflow._utils.logger_utils import get_cli_sdk_logger
from promptflow._utils.utils import _match_reference
from promptflow._utils.yaml_utils import dump_yaml, load_yaml, load_yaml_string
from promptflow.contracts.tool import ToolType
from promptflow.exceptions import ErrorTarget, UserErrorException
def is_github_codespaces():
# Ref:
# https://docs.github.com/en/codespaces/developing-in-a-codespace/default-environment-variables-for-your-codespace
return os.environ.get("CODESPACES", None) == "true" | null |
4,107 | import collections
import datetime
import hashlib
import json
import multiprocessing
import os
import platform
import re
import shutil
import stat
import sys
import tempfile
import uuid
import zipfile
from contextlib import contextmanager
from enum import Enum
from functools import partial
from os import PathLike
from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Tuple, Union
from urllib.parse import urlparse
import keyring
import pydash
from cryptography.fernet import Fernet
from filelock import FileLock
from jinja2 import Template
from keyring.errors import NoKeyringError
from marshmallow import ValidationError
import promptflow
from promptflow._constants import EXTENSION_UA, PF_NO_INTERACTIVE_LOGIN, PF_USER_AGENT, USER_AGENT
from promptflow._sdk._constants import (
AZURE_WORKSPACE_REGEX_FORMAT,
DAG_FILE_NAME,
DEFAULT_ENCODING,
FLOW_META_JSON,
FLOW_META_JSON_GEN_TIMEOUT,
FLOW_TOOLS_JSON,
FLOW_TOOLS_JSON_GEN_TIMEOUT,
HOME_PROMPT_FLOW_DIR,
KEYRING_ENCRYPTION_KEY_NAME,
KEYRING_ENCRYPTION_LOCK_PATH,
KEYRING_SYSTEM,
NODE,
NODE_VARIANTS,
NODES,
PROMPT_FLOW_DIR_NAME,
REFRESH_CONNECTIONS_DIR_LOCK_PATH,
REGISTRY_URI_PREFIX,
REMOTE_URI_PREFIX,
USE_VARIANTS,
VARIANTS,
AzureMLWorkspaceTriad,
CommonYamlFields,
)
from promptflow._sdk._errors import (
DecryptConnectionError,
GenerateFlowMetaJsonError,
GenerateFlowToolsJsonError,
StoreConnectionEncryptionKeyError,
UnsecureConnectionError,
)
from promptflow._sdk._vendor import IgnoreFile, get_ignore_file, get_upload_files_from_folder
from promptflow._utils.context_utils import _change_working_dir, inject_sys_path
from promptflow._utils.dataclass_serializer import serialize
from promptflow._utils.logger_utils import get_cli_sdk_logger
from promptflow._utils.utils import _match_reference
from promptflow._utils.yaml_utils import dump_yaml, load_yaml, load_yaml_string
from promptflow.contracts.tool import ToolType
from promptflow.exceptions import ErrorTarget, UserErrorException
def interactive_credential_disabled():
return os.environ.get(PF_NO_INTERACTIVE_LOGIN, "false").lower() == "true" | null |
4,108 | import collections
import datetime
import hashlib
import json
import multiprocessing
import os
import platform
import re
import shutil
import stat
import sys
import tempfile
import uuid
import zipfile
from contextlib import contextmanager
from enum import Enum
from functools import partial
from os import PathLike
from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Tuple, Union
from urllib.parse import urlparse
import keyring
import pydash
from cryptography.fernet import Fernet
from filelock import FileLock
from jinja2 import Template
from keyring.errors import NoKeyringError
from marshmallow import ValidationError
import promptflow
from promptflow._constants import EXTENSION_UA, PF_NO_INTERACTIVE_LOGIN, PF_USER_AGENT, USER_AGENT
from promptflow._sdk._constants import (
AZURE_WORKSPACE_REGEX_FORMAT,
DAG_FILE_NAME,
DEFAULT_ENCODING,
FLOW_META_JSON,
FLOW_META_JSON_GEN_TIMEOUT,
FLOW_TOOLS_JSON,
FLOW_TOOLS_JSON_GEN_TIMEOUT,
HOME_PROMPT_FLOW_DIR,
KEYRING_ENCRYPTION_KEY_NAME,
KEYRING_ENCRYPTION_LOCK_PATH,
KEYRING_SYSTEM,
NODE,
NODE_VARIANTS,
NODES,
PROMPT_FLOW_DIR_NAME,
REFRESH_CONNECTIONS_DIR_LOCK_PATH,
REGISTRY_URI_PREFIX,
REMOTE_URI_PREFIX,
USE_VARIANTS,
VARIANTS,
AzureMLWorkspaceTriad,
CommonYamlFields,
)
from promptflow._sdk._errors import (
DecryptConnectionError,
GenerateFlowMetaJsonError,
GenerateFlowToolsJsonError,
StoreConnectionEncryptionKeyError,
UnsecureConnectionError,
)
from promptflow._sdk._vendor import IgnoreFile, get_ignore_file, get_upload_files_from_folder
from promptflow._utils.context_utils import _change_working_dir, inject_sys_path
from promptflow._utils.dataclass_serializer import serialize
from promptflow._utils.logger_utils import get_cli_sdk_logger
from promptflow._utils.utils import _match_reference
from promptflow._utils.yaml_utils import dump_yaml, load_yaml, load_yaml_string
from promptflow.contracts.tool import ToolType
from promptflow.exceptions import ErrorTarget, UserErrorException
class ClientUserAgentUtil:
def _get_context(cls):
def get_user_agent(cls):
def append_user_agent(cls, user_agent: Optional[str]):
def update_user_agent_from_env_var(cls):
def update_user_agent_from_config(cls):
def is_from_cli():
from promptflow._cli._user_agent import USER_AGENT as CLI_UA
return CLI_UA in ClientUserAgentUtil.get_user_agent() | null |
4,109 | import collections
import datetime
import hashlib
import json
import multiprocessing
import os
import platform
import re
import shutil
import stat
import sys
import tempfile
import uuid
import zipfile
from contextlib import contextmanager
from enum import Enum
from functools import partial
from os import PathLike
from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Tuple, Union
from urllib.parse import urlparse
import keyring
import pydash
from cryptography.fernet import Fernet
from filelock import FileLock
from jinja2 import Template
from keyring.errors import NoKeyringError
from marshmallow import ValidationError
import promptflow
from promptflow._constants import EXTENSION_UA, PF_NO_INTERACTIVE_LOGIN, PF_USER_AGENT, USER_AGENT
from promptflow._sdk._constants import (
AZURE_WORKSPACE_REGEX_FORMAT,
DAG_FILE_NAME,
DEFAULT_ENCODING,
FLOW_META_JSON,
FLOW_META_JSON_GEN_TIMEOUT,
FLOW_TOOLS_JSON,
FLOW_TOOLS_JSON_GEN_TIMEOUT,
HOME_PROMPT_FLOW_DIR,
KEYRING_ENCRYPTION_KEY_NAME,
KEYRING_ENCRYPTION_LOCK_PATH,
KEYRING_SYSTEM,
NODE,
NODE_VARIANTS,
NODES,
PROMPT_FLOW_DIR_NAME,
REFRESH_CONNECTIONS_DIR_LOCK_PATH,
REGISTRY_URI_PREFIX,
REMOTE_URI_PREFIX,
USE_VARIANTS,
VARIANTS,
AzureMLWorkspaceTriad,
CommonYamlFields,
)
from promptflow._sdk._errors import (
DecryptConnectionError,
GenerateFlowMetaJsonError,
GenerateFlowToolsJsonError,
StoreConnectionEncryptionKeyError,
UnsecureConnectionError,
)
from promptflow._sdk._vendor import IgnoreFile, get_ignore_file, get_upload_files_from_folder
from promptflow._utils.context_utils import _change_working_dir, inject_sys_path
from promptflow._utils.dataclass_serializer import serialize
from promptflow._utils.logger_utils import get_cli_sdk_logger
from promptflow._utils.utils import _match_reference
from promptflow._utils.yaml_utils import dump_yaml, load_yaml, load_yaml_string
from promptflow.contracts.tool import ToolType
from promptflow.exceptions import ErrorTarget, UserErrorException
def is_url(value: Union[PathLike, str]) -> bool:
try:
result = urlparse(str(value))
return all([result.scheme, result.netloc])
except ValueError:
return False
def is_remote_uri(obj) -> bool:
# return True if it's supported remote uri
if isinstance(obj, str):
if obj.startswith(REMOTE_URI_PREFIX):
# azureml: started, azureml:name:version, azureml://xxx
return True
elif is_url(obj):
return True
return False | null |
4,110 | import collections
import datetime
import hashlib
import json
import multiprocessing
import os
import platform
import re
import shutil
import stat
import sys
import tempfile
import uuid
import zipfile
from contextlib import contextmanager
from enum import Enum
from functools import partial
from os import PathLike
from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Tuple, Union
from urllib.parse import urlparse
import keyring
import pydash
from cryptography.fernet import Fernet
from filelock import FileLock
from jinja2 import Template
from keyring.errors import NoKeyringError
from marshmallow import ValidationError
import promptflow
from promptflow._constants import EXTENSION_UA, PF_NO_INTERACTIVE_LOGIN, PF_USER_AGENT, USER_AGENT
from promptflow._sdk._constants import (
AZURE_WORKSPACE_REGEX_FORMAT,
DAG_FILE_NAME,
DEFAULT_ENCODING,
FLOW_META_JSON,
FLOW_META_JSON_GEN_TIMEOUT,
FLOW_TOOLS_JSON,
FLOW_TOOLS_JSON_GEN_TIMEOUT,
HOME_PROMPT_FLOW_DIR,
KEYRING_ENCRYPTION_KEY_NAME,
KEYRING_ENCRYPTION_LOCK_PATH,
KEYRING_SYSTEM,
NODE,
NODE_VARIANTS,
NODES,
PROMPT_FLOW_DIR_NAME,
REFRESH_CONNECTIONS_DIR_LOCK_PATH,
REGISTRY_URI_PREFIX,
REMOTE_URI_PREFIX,
USE_VARIANTS,
VARIANTS,
AzureMLWorkspaceTriad,
CommonYamlFields,
)
from promptflow._sdk._errors import (
DecryptConnectionError,
GenerateFlowMetaJsonError,
GenerateFlowToolsJsonError,
StoreConnectionEncryptionKeyError,
UnsecureConnectionError,
)
from promptflow._sdk._vendor import IgnoreFile, get_ignore_file, get_upload_files_from_folder
from promptflow._utils.context_utils import _change_working_dir, inject_sys_path
from promptflow._utils.dataclass_serializer import serialize
from promptflow._utils.logger_utils import get_cli_sdk_logger
from promptflow._utils.utils import _match_reference
from promptflow._utils.yaml_utils import dump_yaml, load_yaml, load_yaml_string
from promptflow.contracts.tool import ToolType
from promptflow.exceptions import ErrorTarget, UserErrorException
def parse_remote_flow_pattern(flow: object) -> str:
# Check if the input matches the correct pattern
flow_name = None
error_message = (
f"Invalid remote flow pattern, got {flow!r} while expecting "
f"a remote workspace flow like '{REMOTE_URI_PREFIX}<flow-name>', or a remote registry flow like "
f"'{REMOTE_URI_PREFIX}//registries/<registry-name>/models/<flow-name>/versions/<version>'"
)
if not isinstance(flow, str) or not flow.startswith(REMOTE_URI_PREFIX):
raise UserErrorException(error_message)
# check for registry flow pattern
if flow.startswith(REGISTRY_URI_PREFIX):
pattern = r"azureml://registries/.*?/models/(?P<name>.*?)/versions/(?P<version>.*?)$"
match = re.match(pattern, flow)
if not match or len(match.groups()) != 2:
raise UserErrorException(error_message)
flow_name, _ = match.groups()
# check for workspace flow pattern
elif flow.startswith(REMOTE_URI_PREFIX):
pattern = r"azureml:(?P<name>.*?)$"
match = re.match(pattern, flow)
if not match or len(match.groups()) != 1:
raise UserErrorException(error_message)
flow_name = match.groups()[0]
return flow_name | null |
4,111 | import collections
import datetime
import hashlib
import json
import multiprocessing
import os
import platform
import re
import shutil
import stat
import sys
import tempfile
import uuid
import zipfile
from contextlib import contextmanager
from enum import Enum
from functools import partial
from os import PathLike
from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Tuple, Union
from urllib.parse import urlparse
import keyring
import pydash
from cryptography.fernet import Fernet
from filelock import FileLock
from jinja2 import Template
from keyring.errors import NoKeyringError
from marshmallow import ValidationError
import promptflow
from promptflow._constants import EXTENSION_UA, PF_NO_INTERACTIVE_LOGIN, PF_USER_AGENT, USER_AGENT
from promptflow._sdk._constants import (
AZURE_WORKSPACE_REGEX_FORMAT,
DAG_FILE_NAME,
DEFAULT_ENCODING,
FLOW_META_JSON,
FLOW_META_JSON_GEN_TIMEOUT,
FLOW_TOOLS_JSON,
FLOW_TOOLS_JSON_GEN_TIMEOUT,
HOME_PROMPT_FLOW_DIR,
KEYRING_ENCRYPTION_KEY_NAME,
KEYRING_ENCRYPTION_LOCK_PATH,
KEYRING_SYSTEM,
NODE,
NODE_VARIANTS,
NODES,
PROMPT_FLOW_DIR_NAME,
REFRESH_CONNECTIONS_DIR_LOCK_PATH,
REGISTRY_URI_PREFIX,
REMOTE_URI_PREFIX,
USE_VARIANTS,
VARIANTS,
AzureMLWorkspaceTriad,
CommonYamlFields,
)
from promptflow._sdk._errors import (
DecryptConnectionError,
GenerateFlowMetaJsonError,
GenerateFlowToolsJsonError,
StoreConnectionEncryptionKeyError,
UnsecureConnectionError,
)
from promptflow._sdk._vendor import IgnoreFile, get_ignore_file, get_upload_files_from_folder
from promptflow._utils.context_utils import _change_working_dir, inject_sys_path
from promptflow._utils.dataclass_serializer import serialize
from promptflow._utils.logger_utils import get_cli_sdk_logger
from promptflow._utils.utils import _match_reference
from promptflow._utils.yaml_utils import dump_yaml, load_yaml, load_yaml_string
from promptflow.contracts.tool import ToolType
from promptflow.exceptions import ErrorTarget, UserErrorException
read_open = partial(open, mode="r", encoding=DEFAULT_ENCODING)
def json_load(file, parse_const_as_str: bool = False) -> str:
with read_open(file) as f:
if parse_const_as_str is True:
return json.load(f, parse_constant=lambda x: str(x))
else:
return json.load(f) | null |
4,112 | import collections
import datetime
import hashlib
import json
import multiprocessing
import os
import platform
import re
import shutil
import stat
import sys
import tempfile
import uuid
import zipfile
from contextlib import contextmanager
from enum import Enum
from functools import partial
from os import PathLike
from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Tuple, Union
from urllib.parse import urlparse
import keyring
import pydash
from cryptography.fernet import Fernet
from filelock import FileLock
from jinja2 import Template
from keyring.errors import NoKeyringError
from marshmallow import ValidationError
import promptflow
from promptflow._constants import EXTENSION_UA, PF_NO_INTERACTIVE_LOGIN, PF_USER_AGENT, USER_AGENT
from promptflow._sdk._constants import (
AZURE_WORKSPACE_REGEX_FORMAT,
DAG_FILE_NAME,
DEFAULT_ENCODING,
FLOW_META_JSON,
FLOW_META_JSON_GEN_TIMEOUT,
FLOW_TOOLS_JSON,
FLOW_TOOLS_JSON_GEN_TIMEOUT,
HOME_PROMPT_FLOW_DIR,
KEYRING_ENCRYPTION_KEY_NAME,
KEYRING_ENCRYPTION_LOCK_PATH,
KEYRING_SYSTEM,
NODE,
NODE_VARIANTS,
NODES,
PROMPT_FLOW_DIR_NAME,
REFRESH_CONNECTIONS_DIR_LOCK_PATH,
REGISTRY_URI_PREFIX,
REMOTE_URI_PREFIX,
USE_VARIANTS,
VARIANTS,
AzureMLWorkspaceTriad,
CommonYamlFields,
)
from promptflow._sdk._errors import (
DecryptConnectionError,
GenerateFlowMetaJsonError,
GenerateFlowToolsJsonError,
StoreConnectionEncryptionKeyError,
UnsecureConnectionError,
)
from promptflow._sdk._vendor import IgnoreFile, get_ignore_file, get_upload_files_from_folder
from promptflow._utils.context_utils import _change_working_dir, inject_sys_path
from promptflow._utils.dataclass_serializer import serialize
from promptflow._utils.logger_utils import get_cli_sdk_logger
from promptflow._utils.utils import _match_reference
from promptflow._utils.yaml_utils import dump_yaml, load_yaml, load_yaml_string
from promptflow.contracts.tool import ToolType
from promptflow.exceptions import ErrorTarget, UserErrorException
write_open = partial(open, mode="w", encoding=DEFAULT_ENCODING)
def json_dump(obj, file) -> None:
with write_open(file) as f:
json.dump(obj, f, ensure_ascii=False) | null |
4,113 | import collections
import datetime
import hashlib
import json
import multiprocessing
import os
import platform
import re
import shutil
import stat
import sys
import tempfile
import uuid
import zipfile
from contextlib import contextmanager
from enum import Enum
from functools import partial
from os import PathLike
from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Tuple, Union
from urllib.parse import urlparse
import keyring
import pydash
from cryptography.fernet import Fernet
from filelock import FileLock
from jinja2 import Template
from keyring.errors import NoKeyringError
from marshmallow import ValidationError
import promptflow
from promptflow._constants import EXTENSION_UA, PF_NO_INTERACTIVE_LOGIN, PF_USER_AGENT, USER_AGENT
from promptflow._sdk._constants import (
AZURE_WORKSPACE_REGEX_FORMAT,
DAG_FILE_NAME,
DEFAULT_ENCODING,
FLOW_META_JSON,
FLOW_META_JSON_GEN_TIMEOUT,
FLOW_TOOLS_JSON,
FLOW_TOOLS_JSON_GEN_TIMEOUT,
HOME_PROMPT_FLOW_DIR,
KEYRING_ENCRYPTION_KEY_NAME,
KEYRING_ENCRYPTION_LOCK_PATH,
KEYRING_SYSTEM,
NODE,
NODE_VARIANTS,
NODES,
PROMPT_FLOW_DIR_NAME,
REFRESH_CONNECTIONS_DIR_LOCK_PATH,
REGISTRY_URI_PREFIX,
REMOTE_URI_PREFIX,
USE_VARIANTS,
VARIANTS,
AzureMLWorkspaceTriad,
CommonYamlFields,
)
from promptflow._sdk._errors import (
DecryptConnectionError,
GenerateFlowMetaJsonError,
GenerateFlowToolsJsonError,
StoreConnectionEncryptionKeyError,
UnsecureConnectionError,
)
from promptflow._sdk._vendor import IgnoreFile, get_ignore_file, get_upload_files_from_folder
from promptflow._utils.context_utils import _change_working_dir, inject_sys_path
from promptflow._utils.dataclass_serializer import serialize
from promptflow._utils.logger_utils import get_cli_sdk_logger
from promptflow._utils.utils import _match_reference
from promptflow._utils.yaml_utils import dump_yaml, load_yaml, load_yaml_string
from promptflow.contracts.tool import ToolType
from promptflow.exceptions import ErrorTarget, UserErrorException
read_open = partial(open, mode="r", encoding=DEFAULT_ENCODING)
def pd_read_json(file) -> "DataFrame":
import pandas as pd
with read_open(file) as f:
return pd.read_json(f, orient="records", lines=True) | null |
4,114 | import collections
import datetime
import hashlib
import json
import multiprocessing
import os
import platform
import re
import shutil
import stat
import sys
import tempfile
import uuid
import zipfile
from contextlib import contextmanager
from enum import Enum
from functools import partial
from os import PathLike
from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Tuple, Union
from urllib.parse import urlparse
import keyring
import pydash
from cryptography.fernet import Fernet
from filelock import FileLock
from jinja2 import Template
from keyring.errors import NoKeyringError
from marshmallow import ValidationError
import promptflow
from promptflow._constants import EXTENSION_UA, PF_NO_INTERACTIVE_LOGIN, PF_USER_AGENT, USER_AGENT
from promptflow._sdk._constants import (
AZURE_WORKSPACE_REGEX_FORMAT,
DAG_FILE_NAME,
DEFAULT_ENCODING,
FLOW_META_JSON,
FLOW_META_JSON_GEN_TIMEOUT,
FLOW_TOOLS_JSON,
FLOW_TOOLS_JSON_GEN_TIMEOUT,
HOME_PROMPT_FLOW_DIR,
KEYRING_ENCRYPTION_KEY_NAME,
KEYRING_ENCRYPTION_LOCK_PATH,
KEYRING_SYSTEM,
NODE,
NODE_VARIANTS,
NODES,
PROMPT_FLOW_DIR_NAME,
REFRESH_CONNECTIONS_DIR_LOCK_PATH,
REGISTRY_URI_PREFIX,
REMOTE_URI_PREFIX,
USE_VARIANTS,
VARIANTS,
AzureMLWorkspaceTriad,
CommonYamlFields,
)
from promptflow._sdk._errors import (
DecryptConnectionError,
GenerateFlowMetaJsonError,
GenerateFlowToolsJsonError,
StoreConnectionEncryptionKeyError,
UnsecureConnectionError,
)
from promptflow._sdk._vendor import IgnoreFile, get_ignore_file, get_upload_files_from_folder
from promptflow._utils.context_utils import _change_working_dir, inject_sys_path
from promptflow._utils.dataclass_serializer import serialize
from promptflow._utils.logger_utils import get_cli_sdk_logger
from promptflow._utils.utils import _match_reference
from promptflow._utils.yaml_utils import dump_yaml, load_yaml, load_yaml_string
from promptflow.contracts.tool import ToolType
from promptflow.exceptions import ErrorTarget, UserErrorException
def get_mac_address() -> str:
"""Obtain all MAC addresses, then sort and concatenate them."""
try:
import psutil
mac_address = []
net_addresses = psutil.net_if_addrs()
# Obtain all MAC addresses, then sort and concatenate them
net_address_list = sorted(net_addresses.items()) # sort by name
for name, net_address in net_address_list:
for net_interface in net_address:
if net_interface.family == psutil.AF_LINK and net_interface.address != "00-00-00-00-00-00":
mac_address.append(net_interface.address)
return ":".join(mac_address)
except Exception as e:
logger.debug(f"get mac id error: {str(e)}")
return ""
def get_system_info() -> Tuple[str, str, str]:
"""Get the host name, system, and machine."""
try:
import platform
return platform.node(), platform.system(), platform.machine()
except Exception as e:
logger.debug(f"get host name error: {str(e)}")
return "", "", ""
def gen_uuid_by_compute_info() -> Union[str, None]:
mac_address = get_mac_address()
host_name, system, machine = get_system_info()
if mac_address:
# Use sha256 convert host_name+system+machine to a fixed length string
# and concatenate it after the mac address to ensure that the concatenated string is unique.
system_info_hash = hashlib.sha256((host_name + system + machine).encode()).hexdigest()
compute_info_hash = hashlib.sha256((mac_address + system_info_hash).encode()).hexdigest()
return str(uuid.uuid5(uuid.NAMESPACE_OID, compute_info_hash))
return str(uuid.uuid4()) | null |
4,115 | import collections
import datetime
import hashlib
import json
import multiprocessing
import os
import platform
import re
import shutil
import stat
import sys
import tempfile
import uuid
import zipfile
from contextlib import contextmanager
from enum import Enum
from functools import partial
from os import PathLike
from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Tuple, Union
from urllib.parse import urlparse
import keyring
import pydash
from cryptography.fernet import Fernet
from filelock import FileLock
from jinja2 import Template
from keyring.errors import NoKeyringError
from marshmallow import ValidationError
import promptflow
from promptflow._constants import EXTENSION_UA, PF_NO_INTERACTIVE_LOGIN, PF_USER_AGENT, USER_AGENT
from promptflow._sdk._constants import (
AZURE_WORKSPACE_REGEX_FORMAT,
DAG_FILE_NAME,
DEFAULT_ENCODING,
FLOW_META_JSON,
FLOW_META_JSON_GEN_TIMEOUT,
FLOW_TOOLS_JSON,
FLOW_TOOLS_JSON_GEN_TIMEOUT,
HOME_PROMPT_FLOW_DIR,
KEYRING_ENCRYPTION_KEY_NAME,
KEYRING_ENCRYPTION_LOCK_PATH,
KEYRING_SYSTEM,
NODE,
NODE_VARIANTS,
NODES,
PROMPT_FLOW_DIR_NAME,
REFRESH_CONNECTIONS_DIR_LOCK_PATH,
REGISTRY_URI_PREFIX,
REMOTE_URI_PREFIX,
USE_VARIANTS,
VARIANTS,
AzureMLWorkspaceTriad,
CommonYamlFields,
)
from promptflow._sdk._errors import (
DecryptConnectionError,
GenerateFlowMetaJsonError,
GenerateFlowToolsJsonError,
StoreConnectionEncryptionKeyError,
UnsecureConnectionError,
)
from promptflow._sdk._vendor import IgnoreFile, get_ignore_file, get_upload_files_from_folder
from promptflow._utils.context_utils import _change_working_dir, inject_sys_path
from promptflow._utils.dataclass_serializer import serialize
from promptflow._utils.logger_utils import get_cli_sdk_logger
from promptflow._utils.utils import _match_reference
from promptflow._utils.yaml_utils import dump_yaml, load_yaml, load_yaml_string
from promptflow.contracts.tool import ToolType
from promptflow.exceptions import ErrorTarget, UserErrorException
def convert_time_unix_nano_to_timestamp(time_unix_nano: str) -> str:
nanoseconds = int(time_unix_nano)
seconds = nanoseconds / 1_000_000_000
timestamp = datetime.datetime.utcfromtimestamp(seconds)
return timestamp.isoformat() | null |
4,116 | import collections
import datetime
import hashlib
import json
import multiprocessing
import os
import platform
import re
import shutil
import stat
import sys
import tempfile
import uuid
import zipfile
from contextlib import contextmanager
from enum import Enum
from functools import partial
from os import PathLike
from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Tuple, Union
from urllib.parse import urlparse
import keyring
import pydash
from cryptography.fernet import Fernet
from filelock import FileLock
from jinja2 import Template
from keyring.errors import NoKeyringError
from marshmallow import ValidationError
import promptflow
from promptflow._constants import EXTENSION_UA, PF_NO_INTERACTIVE_LOGIN, PF_USER_AGENT, USER_AGENT
from promptflow._sdk._constants import (
AZURE_WORKSPACE_REGEX_FORMAT,
DAG_FILE_NAME,
DEFAULT_ENCODING,
FLOW_META_JSON,
FLOW_META_JSON_GEN_TIMEOUT,
FLOW_TOOLS_JSON,
FLOW_TOOLS_JSON_GEN_TIMEOUT,
HOME_PROMPT_FLOW_DIR,
KEYRING_ENCRYPTION_KEY_NAME,
KEYRING_ENCRYPTION_LOCK_PATH,
KEYRING_SYSTEM,
NODE,
NODE_VARIANTS,
NODES,
PROMPT_FLOW_DIR_NAME,
REFRESH_CONNECTIONS_DIR_LOCK_PATH,
REGISTRY_URI_PREFIX,
REMOTE_URI_PREFIX,
USE_VARIANTS,
VARIANTS,
AzureMLWorkspaceTriad,
CommonYamlFields,
)
from promptflow._sdk._errors import (
DecryptConnectionError,
GenerateFlowMetaJsonError,
GenerateFlowToolsJsonError,
StoreConnectionEncryptionKeyError,
UnsecureConnectionError,
)
from promptflow._sdk._vendor import IgnoreFile, get_ignore_file, get_upload_files_from_folder
from promptflow._utils.context_utils import _change_working_dir, inject_sys_path
from promptflow._utils.dataclass_serializer import serialize
from promptflow._utils.logger_utils import get_cli_sdk_logger
from promptflow._utils.utils import _match_reference
from promptflow._utils.yaml_utils import dump_yaml, load_yaml, load_yaml_string
from promptflow.contracts.tool import ToolType
from promptflow.exceptions import ErrorTarget, UserErrorException
def parse_kv_from_pb_attribute(attribute: Dict) -> Tuple[str, str]:
attr_key = attribute["key"]
# suppose all values are flattened here
# so simply regard the first value as the attribute value
attr_value = list(attribute["value"].values())[0]
return attr_key, attr_value
def flatten_pb_attributes(attributes: List[Dict]) -> Dict:
flattened_attributes = {}
for attribute in attributes:
attr_key, attr_value = parse_kv_from_pb_attribute(attribute)
flattened_attributes[attr_key] = attr_value
return flattened_attributes | null |
4,117 | import collections
import datetime
import hashlib
import json
import multiprocessing
import os
import platform
import re
import shutil
import stat
import sys
import tempfile
import uuid
import zipfile
from contextlib import contextmanager
from enum import Enum
from functools import partial
from os import PathLike
from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Tuple, Union
from urllib.parse import urlparse
import keyring
import pydash
from cryptography.fernet import Fernet
from filelock import FileLock
from jinja2 import Template
from keyring.errors import NoKeyringError
from marshmallow import ValidationError
import promptflow
from promptflow._constants import EXTENSION_UA, PF_NO_INTERACTIVE_LOGIN, PF_USER_AGENT, USER_AGENT
from promptflow._sdk._constants import (
AZURE_WORKSPACE_REGEX_FORMAT,
DAG_FILE_NAME,
DEFAULT_ENCODING,
FLOW_META_JSON,
FLOW_META_JSON_GEN_TIMEOUT,
FLOW_TOOLS_JSON,
FLOW_TOOLS_JSON_GEN_TIMEOUT,
HOME_PROMPT_FLOW_DIR,
KEYRING_ENCRYPTION_KEY_NAME,
KEYRING_ENCRYPTION_LOCK_PATH,
KEYRING_SYSTEM,
NODE,
NODE_VARIANTS,
NODES,
PROMPT_FLOW_DIR_NAME,
REFRESH_CONNECTIONS_DIR_LOCK_PATH,
REGISTRY_URI_PREFIX,
REMOTE_URI_PREFIX,
USE_VARIANTS,
VARIANTS,
AzureMLWorkspaceTriad,
CommonYamlFields,
)
from promptflow._sdk._errors import (
DecryptConnectionError,
GenerateFlowMetaJsonError,
GenerateFlowToolsJsonError,
StoreConnectionEncryptionKeyError,
UnsecureConnectionError,
)
from promptflow._sdk._vendor import IgnoreFile, get_ignore_file, get_upload_files_from_folder
from promptflow._utils.context_utils import _change_working_dir, inject_sys_path
from promptflow._utils.dataclass_serializer import serialize
from promptflow._utils.logger_utils import get_cli_sdk_logger
from promptflow._utils.utils import _match_reference
from promptflow._utils.yaml_utils import dump_yaml, load_yaml, load_yaml_string
from promptflow.contracts.tool import ToolType
from promptflow.exceptions import ErrorTarget, UserErrorException
def parse_otel_span_status_code(value: int) -> str:
# map int value to string
# https://github.com/open-telemetry/opentelemetry-specification/blob/v1.22.0/specification/trace/api.md#set-status
# https://github.com/open-telemetry/opentelemetry-python/blob/v1.22.0/opentelemetry-api/src/opentelemetry/trace/status.py#L22-L32
if value == 0:
return "Unset"
elif value == 1:
return "Ok"
else:
return "Error" | null |
4,118 | import collections
import datetime
import hashlib
import json
import multiprocessing
import os
import platform
import re
import shutil
import stat
import sys
import tempfile
import uuid
import zipfile
from contextlib import contextmanager
from enum import Enum
from functools import partial
from os import PathLike
from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Tuple, Union
from urllib.parse import urlparse
import keyring
import pydash
from cryptography.fernet import Fernet
from filelock import FileLock
from jinja2 import Template
from keyring.errors import NoKeyringError
from marshmallow import ValidationError
import promptflow
from promptflow._constants import EXTENSION_UA, PF_NO_INTERACTIVE_LOGIN, PF_USER_AGENT, USER_AGENT
from promptflow._sdk._constants import (
AZURE_WORKSPACE_REGEX_FORMAT,
DAG_FILE_NAME,
DEFAULT_ENCODING,
FLOW_META_JSON,
FLOW_META_JSON_GEN_TIMEOUT,
FLOW_TOOLS_JSON,
FLOW_TOOLS_JSON_GEN_TIMEOUT,
HOME_PROMPT_FLOW_DIR,
KEYRING_ENCRYPTION_KEY_NAME,
KEYRING_ENCRYPTION_LOCK_PATH,
KEYRING_SYSTEM,
NODE,
NODE_VARIANTS,
NODES,
PROMPT_FLOW_DIR_NAME,
REFRESH_CONNECTIONS_DIR_LOCK_PATH,
REGISTRY_URI_PREFIX,
REMOTE_URI_PREFIX,
USE_VARIANTS,
VARIANTS,
AzureMLWorkspaceTriad,
CommonYamlFields,
)
from promptflow._sdk._errors import (
DecryptConnectionError,
GenerateFlowMetaJsonError,
GenerateFlowToolsJsonError,
StoreConnectionEncryptionKeyError,
UnsecureConnectionError,
)
from promptflow._sdk._vendor import IgnoreFile, get_ignore_file, get_upload_files_from_folder
from promptflow._utils.context_utils import _change_working_dir, inject_sys_path
from promptflow._utils.dataclass_serializer import serialize
from promptflow._utils.logger_utils import get_cli_sdk_logger
from promptflow._utils.utils import _match_reference
from promptflow._utils.yaml_utils import dump_yaml, load_yaml, load_yaml_string
from promptflow.contracts.tool import ToolType
from promptflow.exceptions import ErrorTarget, UserErrorException
def _generate_flow_meta(
flow_directory: Path,
source_path: str,
entry: str,
timeout: int,
*,
load_in_subprocess: bool = True,
) -> Dict[str, dict]:
"""Generate tool meta from files.
:param flow_directory: flow directory
:param tools: tool list
:param raise_error: whether raise error when generate meta failed
:param timeout: timeout for generate meta
:param include_errors_in_output: whether include errors in output
:param load_in_subprocess: whether load tool meta with subprocess to prevent system path disturb. Default is True.
If set to False, will load tool meta in sync mode and timeout need to be handled outside current process.
:return: tool meta dict
"""
if load_in_subprocess:
# use multiprocess generate to avoid system path disturb
manager = multiprocessing.Manager()
meta_dict = manager.dict()
exception_list = manager.list()
p = multiprocessing.Process(
target=_generate_meta_from_file, args=(flow_directory, source_path, entry, meta_dict, exception_list)
)
p.start()
p.join(timeout=timeout)
if p.is_alive():
logger.warning(f"Generate meta timeout after {timeout} seconds, terminate the process.")
p.terminate()
p.join()
else:
meta_dict, exception_list = {}, []
# There is no built-in method to forcefully stop a running thread/coroutine in Python
# because abruptly stopping a thread can cause issues like resource leaks,
# deadlocks, or inconsistent states.
# Caller needs to handle the timeout outside current process.
logger.warning(
"Generate meta in current process and timeout won't take effect. "
"Please handle timeout manually outside current process."
)
_generate_meta_from_file(flow_directory, source_path, entry, meta_dict, exception_list)
# directly raise error if failed to generate meta
if len(exception_list) > 0:
error_message = "Generate meta failed, detail error:\n" + str(exception_list)
raise GenerateFlowMetaJsonError(error_message)
return dict(meta_dict)
The provided code snippet includes necessary dependencies for implementing the `generate_flow_meta` function. Write a Python function `def generate_flow_meta( flow_directory: Union[str, Path], source_path: str, entry: str, dump: bool = True, timeout: int = FLOW_META_JSON_GEN_TIMEOUT, load_in_subprocess: bool = True, ) -> dict` to solve the following problem:
Generate flow.json for a flow directory.
Here is the function:
def generate_flow_meta(
flow_directory: Union[str, Path],
source_path: str,
entry: str,
dump: bool = True,
timeout: int = FLOW_META_JSON_GEN_TIMEOUT,
load_in_subprocess: bool = True,
) -> dict:
"""Generate flow.json for a flow directory."""
flow_meta = _generate_flow_meta(
flow_directory=flow_directory,
source_path=source_path,
entry=entry,
timeout=timeout,
load_in_subprocess=load_in_subprocess,
)
if dump:
# dump as flow.tools.json
promptflow_folder = flow_directory / PROMPT_FLOW_DIR_NAME
promptflow_folder.mkdir(exist_ok=True)
with open(promptflow_folder / FLOW_META_JSON, mode="w", encoding=DEFAULT_ENCODING) as f:
json.dump(flow_meta, f, indent=4)
return flow_meta | Generate flow.json for a flow directory. |
4,119 | import collections
import datetime
import hashlib
import json
import multiprocessing
import os
import platform
import re
import shutil
import stat
import sys
import tempfile
import uuid
import zipfile
from contextlib import contextmanager
from enum import Enum
from functools import partial
from os import PathLike
from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Tuple, Union
from urllib.parse import urlparse
import keyring
import pydash
from cryptography.fernet import Fernet
from filelock import FileLock
from jinja2 import Template
from keyring.errors import NoKeyringError
from marshmallow import ValidationError
import promptflow
from promptflow._constants import EXTENSION_UA, PF_NO_INTERACTIVE_LOGIN, PF_USER_AGENT, USER_AGENT
from promptflow._sdk._constants import (
AZURE_WORKSPACE_REGEX_FORMAT,
DAG_FILE_NAME,
DEFAULT_ENCODING,
FLOW_META_JSON,
FLOW_META_JSON_GEN_TIMEOUT,
FLOW_TOOLS_JSON,
FLOW_TOOLS_JSON_GEN_TIMEOUT,
HOME_PROMPT_FLOW_DIR,
KEYRING_ENCRYPTION_KEY_NAME,
KEYRING_ENCRYPTION_LOCK_PATH,
KEYRING_SYSTEM,
NODE,
NODE_VARIANTS,
NODES,
PROMPT_FLOW_DIR_NAME,
REFRESH_CONNECTIONS_DIR_LOCK_PATH,
REGISTRY_URI_PREFIX,
REMOTE_URI_PREFIX,
USE_VARIANTS,
VARIANTS,
AzureMLWorkspaceTriad,
CommonYamlFields,
)
from promptflow._sdk._errors import (
DecryptConnectionError,
GenerateFlowMetaJsonError,
GenerateFlowToolsJsonError,
StoreConnectionEncryptionKeyError,
UnsecureConnectionError,
)
from promptflow._sdk._vendor import IgnoreFile, get_ignore_file, get_upload_files_from_folder
from promptflow._utils.context_utils import _change_working_dir, inject_sys_path
from promptflow._utils.dataclass_serializer import serialize
from promptflow._utils.logger_utils import get_cli_sdk_logger
from promptflow._utils.utils import _match_reference
from promptflow._utils.yaml_utils import dump_yaml, load_yaml, load_yaml_string
from promptflow.contracts.tool import ToolType
from promptflow.exceptions import ErrorTarget, UserErrorException
def extract_workspace_triad_from_trace_provider(trace_provider: str) -> AzureMLWorkspaceTriad:
match = re.match(AZURE_WORKSPACE_REGEX_FORMAT, trace_provider)
if not match or len(match.groups()) != 5:
raise ValueError(
"Malformed trace provider string, expected azureml://subscriptions/<subscription_id>/"
"resourceGroups/<resource_group>/providers/Microsoft.MachineLearningServices/"
f"workspaces/<workspace_name>, got {trace_provider}"
)
subscription_id = match.group(1)
resource_group_name = match.group(3)
workspace_name = match.group(5)
return AzureMLWorkspaceTriad(subscription_id, resource_group_name, workspace_name) | null |
4,120 | import collections
import datetime
import hashlib
import json
import multiprocessing
import os
import platform
import re
import shutil
import stat
import sys
import tempfile
import uuid
import zipfile
from contextlib import contextmanager
from enum import Enum
from functools import partial
from os import PathLike
from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Tuple, Union
from urllib.parse import urlparse
import keyring
import pydash
from cryptography.fernet import Fernet
from filelock import FileLock
from jinja2 import Template
from keyring.errors import NoKeyringError
from marshmallow import ValidationError
import promptflow
from promptflow._constants import EXTENSION_UA, PF_NO_INTERACTIVE_LOGIN, PF_USER_AGENT, USER_AGENT
from promptflow._sdk._constants import (
AZURE_WORKSPACE_REGEX_FORMAT,
DAG_FILE_NAME,
DEFAULT_ENCODING,
FLOW_META_JSON,
FLOW_META_JSON_GEN_TIMEOUT,
FLOW_TOOLS_JSON,
FLOW_TOOLS_JSON_GEN_TIMEOUT,
HOME_PROMPT_FLOW_DIR,
KEYRING_ENCRYPTION_KEY_NAME,
KEYRING_ENCRYPTION_LOCK_PATH,
KEYRING_SYSTEM,
NODE,
NODE_VARIANTS,
NODES,
PROMPT_FLOW_DIR_NAME,
REFRESH_CONNECTIONS_DIR_LOCK_PATH,
REGISTRY_URI_PREFIX,
REMOTE_URI_PREFIX,
USE_VARIANTS,
VARIANTS,
AzureMLWorkspaceTriad,
CommonYamlFields,
)
from promptflow._sdk._errors import (
DecryptConnectionError,
GenerateFlowMetaJsonError,
GenerateFlowToolsJsonError,
StoreConnectionEncryptionKeyError,
UnsecureConnectionError,
)
from promptflow._sdk._vendor import IgnoreFile, get_ignore_file, get_upload_files_from_folder
from promptflow._utils.context_utils import _change_working_dir, inject_sys_path
from promptflow._utils.dataclass_serializer import serialize
from promptflow._utils.logger_utils import get_cli_sdk_logger
from promptflow._utils.utils import _match_reference
from promptflow._utils.yaml_utils import dump_yaml, load_yaml, load_yaml_string
from promptflow.contracts.tool import ToolType
from promptflow.exceptions import ErrorTarget, UserErrorException
def overwrite_null_std_logger():
# For the process started in detach mode, stdout/stderr will be none.
# To avoid exception to stdout/stderr calls in the dependency package, point stdout/stderr to devnull.
if sys.stdout is None:
sys.stdout = open(os.devnull, "w")
if sys.stderr is None:
sys.stderr = sys.stdout | null |
4,121 | import json
import os
import time
import base64
import zlib
from flask import jsonify, request
from promptflow._sdk._serving._errors import (
JsonPayloadRequiredForMultipleInputFields,
MissingRequiredFlowInput,
NotAcceptable,
)
from promptflow._utils.exception_utils import ErrorResponse, ExceptionPresenter
from promptflow.contracts.flow import Flow as FlowContract
from promptflow.exceptions import ErrorTarget
def load_request_data(flow, raw_data, logger):
try:
data = json.loads(raw_data)
except Exception:
input = None
if flow.inputs.keys().__len__() > 1:
# this should only work if there's only 1 input field, otherwise it will fail
# TODO: add a check to make sure there's only 1 input field
message = (
"Promptflow executor received non json data, but there's more than 1 input fields, "
"please use json request data instead."
)
raise JsonPayloadRequiredForMultipleInputFields(message, target=ErrorTarget.SERVING_APP)
if isinstance(raw_data, bytes) or isinstance(raw_data, bytearray):
input = str(raw_data, "UTF-8")
elif isinstance(raw_data, str):
input = raw_data
default_key = list(flow.inputs.keys())[0]
logger.debug(f"Promptflow executor received non json data: {input}, default key: {default_key}")
data = {default_key: input}
return data | null |
4,122 | import json
import os
import time
import base64
import zlib
from flask import jsonify, request
from promptflow._sdk._serving._errors import (
JsonPayloadRequiredForMultipleInputFields,
MissingRequiredFlowInput,
NotAcceptable,
)
from promptflow._utils.exception_utils import ErrorResponse, ExceptionPresenter
from promptflow.contracts.flow import Flow as FlowContract
from promptflow.exceptions import ErrorTarget
The provided code snippet includes necessary dependencies for implementing the `validate_request_data` function. Write a Python function `def validate_request_data(flow, data)` to solve the following problem:
Validate required request data is provided.
Here is the function:
def validate_request_data(flow, data):
"""Validate required request data is provided."""
# TODO: Note that we don't have default flow input presently, all of the default is None.
required_inputs = [k for k, v in flow.inputs.items() if v.default is None]
missing_inputs = [k for k in required_inputs if k not in data]
if missing_inputs:
raise MissingRequiredFlowInput(
f"Required input fields {missing_inputs} are missing in request data {data!r}",
target=ErrorTarget.SERVING_APP,
) | Validate required request data is provided. |
4,123 | import json
import os
import time
import base64
import zlib
from flask import jsonify, request
from promptflow._sdk._serving._errors import (
JsonPayloadRequiredForMultipleInputFields,
MissingRequiredFlowInput,
NotAcceptable,
)
from promptflow._utils.exception_utils import ErrorResponse, ExceptionPresenter
from promptflow.contracts.flow import Flow as FlowContract
from promptflow.exceptions import ErrorTarget
The provided code snippet includes necessary dependencies for implementing the `streaming_response_required` function. Write a Python function `def streaming_response_required()` to solve the following problem:
Check if streaming response is required.
Here is the function:
def streaming_response_required():
"""Check if streaming response is required."""
return "text/event-stream" in request.accept_mimetypes.values() | Check if streaming response is required. |
4,124 | import json
import os
import time
import base64
import zlib
from flask import jsonify, request
from promptflow._sdk._serving._errors import (
JsonPayloadRequiredForMultipleInputFields,
MissingRequiredFlowInput,
NotAcceptable,
)
from promptflow._utils.exception_utils import ErrorResponse, ExceptionPresenter
from promptflow.contracts.flow import Flow as FlowContract
from promptflow.exceptions import ErrorTarget
def get_sample_json(project_path, logger):
# load swagger sample if exists
sample_file = os.path.join(project_path, "samples.json")
if not os.path.exists(sample_file):
return None
logger.info("Promptflow sample file detected.")
with open(sample_file, "r", encoding="UTF-8") as f:
sample = json.load(f)
return sample | null |
4,125 | import json
import os
import time
import base64
import zlib
from flask import jsonify, request
from promptflow._sdk._serving._errors import (
JsonPayloadRequiredForMultipleInputFields,
MissingRequiredFlowInput,
NotAcceptable,
)
from promptflow._utils.exception_utils import ErrorResponse, ExceptionPresenter
from promptflow.contracts.flow import Flow as FlowContract
from promptflow.exceptions import ErrorTarget
The provided code snippet includes necessary dependencies for implementing the `get_output_fields_to_remove` function. Write a Python function `def get_output_fields_to_remove(flow: FlowContract, logger) -> list` to solve the following problem:
get output fields to remove.
Here is the function:
def get_output_fields_to_remove(flow: FlowContract, logger) -> list:
"""get output fields to remove."""
included_outputs = os.getenv("PROMPTFLOW_RESPONSE_INCLUDED_FIELDS", None)
if included_outputs:
logger.info(f"Response included fields: {included_outputs}")
res = json.loads(included_outputs)
return [k for k, v in flow.outputs.items() if k not in res]
return [k for k, v in flow.outputs.items() if v.evaluation_only] | get output fields to remove. |
4,126 | import json
import os
import time
import base64
import zlib
from flask import jsonify, request
from promptflow._sdk._serving._errors import (
JsonPayloadRequiredForMultipleInputFields,
MissingRequiredFlowInput,
NotAcceptable,
)
from promptflow._utils.exception_utils import ErrorResponse, ExceptionPresenter
from promptflow.contracts.flow import Flow as FlowContract
from promptflow.exceptions import ErrorTarget
def handle_error_to_response(e, logger):
presenter = ExceptionPresenter.create(e)
logger.error(f"Promptflow serving app error: {presenter.to_dict()}")
logger.error(f"Promptflow serving error traceback: {presenter.formatted_traceback}")
resp = ErrorResponse(presenter.to_dict())
response_code = resp.response_code
# The http response code for NotAcceptable is 406.
# Currently the error framework does not allow response code overriding,
# we add a check here to override the response code.
# TODO: Consider how to embed this logic into the error framework.
if isinstance(e, NotAcceptable):
response_code = 406
return jsonify(resp.to_simplified_dict()), response_code | null |
4,127 | import json
import os
import time
import base64
import zlib
from flask import jsonify, request
from promptflow._sdk._serving._errors import (
JsonPayloadRequiredForMultipleInputFields,
MissingRequiredFlowInput,
NotAcceptable,
)
from promptflow._utils.exception_utils import ErrorResponse, ExceptionPresenter
from promptflow.contracts.flow import Flow as FlowContract
from promptflow.exceptions import ErrorTarget
def get_pf_serving_env(env_key: str):
if len(env_key) == 0:
return None
value = os.getenv(env_key, None)
if value is None and env_key.startswith("PROMPTFLOW_"):
value = os.getenv(env_key.replace("PROMPTFLOW_", "PF_"), None)
return value | null |
4,128 | import json
import os
import time
import base64
import zlib
from flask import jsonify, request
from promptflow._sdk._serving._errors import (
JsonPayloadRequiredForMultipleInputFields,
MissingRequiredFlowInput,
NotAcceptable,
)
from promptflow._utils.exception_utils import ErrorResponse, ExceptionPresenter
from promptflow.contracts.flow import Flow as FlowContract
from promptflow.exceptions import ErrorTarget
def get_cost_up_to_now(start_time: float):
return (time.time() - start_time) * 1000 | null |
4,129 | import json
import os
import time
import base64
import zlib
from flask import jsonify, request
from promptflow._sdk._serving._errors import (
JsonPayloadRequiredForMultipleInputFields,
MissingRequiredFlowInput,
NotAcceptable,
)
from promptflow._utils.exception_utils import ErrorResponse, ExceptionPresenter
from promptflow.contracts.flow import Flow as FlowContract
from promptflow.exceptions import ErrorTarget
def enable_monitoring(func):
func._enable_monitoring = True
return func | null |
4,130 | import json
import os
import time
import base64
import zlib
from flask import jsonify, request
from promptflow._sdk._serving._errors import (
JsonPayloadRequiredForMultipleInputFields,
MissingRequiredFlowInput,
NotAcceptable,
)
from promptflow._utils.exception_utils import ErrorResponse, ExceptionPresenter
from promptflow.contracts.flow import Flow as FlowContract
from promptflow.exceptions import ErrorTarget
def normalize_connection_name(connection_name: str):
return connection_name.replace(" ", "_") | null |
4,131 | import json
import os
import time
import base64
import zlib
from flask import jsonify, request
from promptflow._sdk._serving._errors import (
JsonPayloadRequiredForMultipleInputFields,
MissingRequiredFlowInput,
NotAcceptable,
)
from promptflow._utils.exception_utils import ErrorResponse, ExceptionPresenter
from promptflow.contracts.flow import Flow as FlowContract
from promptflow.exceptions import ErrorTarget
def decode_dict(data: str) -> dict:
# str -> bytes
data = data.encode()
zipped_conns = base64.b64decode(data)
# gzip decode
conns_data = zlib.decompress(zipped_conns, 16 + zlib.MAX_WBITS)
return json.loads(conns_data.decode()) | null |
4,132 | import json
import os
import time
import base64
import zlib
from flask import jsonify, request
from promptflow._sdk._serving._errors import (
JsonPayloadRequiredForMultipleInputFields,
MissingRequiredFlowInput,
NotAcceptable,
)
from promptflow._utils.exception_utils import ErrorResponse, ExceptionPresenter
from promptflow.contracts.flow import Flow as FlowContract
from promptflow.exceptions import ErrorTarget
def encode_dict(data: dict) -> str:
# json encode
data = json.dumps(data)
# gzip compress
gzip_compress = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)
zipped_data = gzip_compress.compress(data.encode()) + gzip_compress.flush()
# base64 encode
b64_data = base64.b64encode(zipped_data)
# bytes -> str
return b64_data.decode() | null |
4,133 | import json
import os
import re
from typing import Any, Tuple
from promptflow._sdk._serving._errors import InvalidConnectionData, MissingConnectionProvider
from promptflow._sdk._serving.extension.default_extension import AppExtension
from promptflow._sdk._serving.monitor.data_collector import FlowDataCollector
from promptflow._sdk._serving.monitor.flow_monitor import FlowMonitor
from promptflow._sdk._serving.monitor.metrics import MetricsRecorder
from promptflow._sdk._serving.monitor.mdc_exporter import MdcExporter
from promptflow._sdk._serving.utils import decode_dict, get_pf_serving_env, normalize_connection_name
from promptflow._utils.retry_utils import retry
from promptflow._version import VERSION
from promptflow.contracts.flow import Flow
def _get_managed_identity_credential_with_retry(**kwargs):
from azure.identity import ManagedIdentityCredential
from azure.identity._constants import EnvironmentVariables
class ManagedIdentityCredentialWithRetry(ManagedIdentityCredential):
def __init__(self, **kwargs: Any) -> None:
client_id = kwargs.pop("client_id", None) or os.environ.get(EnvironmentVariables.AZURE_CLIENT_ID)
super().__init__(client_id=client_id, **kwargs)
@retry(Exception)
def get_token(self, *scopes, **kwargs):
return super().get_token(*scopes, **kwargs)
return ManagedIdentityCredentialWithRetry(**kwargs) | null |
4,134 | import json
import logging
import mimetypes
import os
from pathlib import Path
from typing import Dict
from flask import Flask, g, jsonify, request
from promptflow._sdk._load_functions import load_flow
from promptflow._sdk._serving.extension.extension_factory import ExtensionFactory
from promptflow._sdk._serving.flow_invoker import FlowInvoker
from promptflow._sdk._serving.response_creator import ResponseCreator
from promptflow._sdk._serving.utils import (
enable_monitoring,
get_output_fields_to_remove,
get_sample_json,
handle_error_to_response,
load_request_data,
streaming_response_required,
)
from promptflow._sdk._utils import setup_user_agent_to_operation_context
from promptflow._utils.exception_utils import ErrorResponse
from promptflow._utils.logger_utils import LoggerFactory
from promptflow._version import VERSION
from promptflow.contracts.run_info import Status
from promptflow.exceptions import SystemErrorException
from promptflow.storage._run_storage import DummyRunStorage
from .swagger import generate_swagger
logger = LoggerFactory.get_logger("pfserving-app", target_stdout=True)
class PromptflowServingApp(Flask):
def init(self, **kwargs):
with self.app_context():
# default to local, can be override when creating the app
self.extension = ExtensionFactory.create_extension(logger, **kwargs)
self.flow_invoker: FlowInvoker = None
# parse promptflow project path
self.project_path = self.extension.get_flow_project_path()
logger.info(f"Project path: {self.project_path}")
self.flow_entity = load_flow(self.project_path)
self.flow = self.flow_entity._init_executable()
# enable environment_variables
environment_variables = kwargs.get("environment_variables", {})
os.environ.update(environment_variables)
default_environment_variables = self.flow.get_environment_variables_with_overrides()
self.set_default_environment_variables(default_environment_variables)
# load trace exporters
trace_exporters = self.extension.get_trace_exporters(self.project_path)
if trace_exporters:
logger.info(f"Enable {len(trace_exporters)} trace exporters.")
from opentelemetry import trace
from opentelemetry.sdk.resources import SERVICE_NAME, Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
resource = Resource(
attributes={
SERVICE_NAME: "promptflow",
}
)
trace.set_tracer_provider(TracerProvider(resource=resource))
provider = trace.get_tracer_provider()
for exporter in trace_exporters:
provider.add_span_processor(BatchSpanProcessor(exporter))
self.flow_name = self.extension.get_flow_name()
self.flow.name = self.flow_name
conn_data_override, conn_name_override = self.extension.get_override_connections(self.flow)
self.connections_override = conn_data_override
self.connections_name_override = conn_name_override
self.flow_monitor = self.extension.get_flow_monitor()
self.connection_provider = self.extension.get_connection_provider()
self.credential = self.extension.get_credential()
self.sample = get_sample_json(self.project_path, logger)
self.init_swagger()
# try to initialize the flow invoker
try:
self.init_invoker_if_not_exist()
except Exception as e:
if self.extension.raise_ex_on_invoker_initialization_failure(e):
raise e
# ensure response has the correct content type
mimetypes.add_type("application/javascript", ".js")
mimetypes.add_type("text/css", ".css")
setup_user_agent_to_operation_context(self.extension.get_user_agent())
add_default_routes(self)
# register blueprints
blue_prints = self.extension.get_blueprints()
for blue_print in blue_prints:
self.register_blueprint(blue_print)
def init_invoker_if_not_exist(self):
if self.flow_invoker:
return
logger.info("Promptflow executor starts initializing...")
self.flow_invoker = FlowInvoker(
self.project_path,
connection_provider=self.connection_provider,
streaming=streaming_response_required,
raise_ex=False,
connections=self.connections_override,
connections_name_overrides=self.connections_name_override,
# for serving, we don't need to persist intermediate result, this is to avoid memory leak.
storage=DummyRunStorage(),
credential=self.credential,
)
self.flow = self.flow_invoker.flow
# Set the flow name as folder name
self.flow.name = self.flow_name
self.response_fields_to_remove = get_output_fields_to_remove(self.flow, logger)
logger.info("Promptflow executor initializing succeed!")
def init_swagger(self):
self.response_fields_to_remove = get_output_fields_to_remove(self.flow, logger)
self.swagger = generate_swagger(self.flow, self.sample, self.response_fields_to_remove)
def set_default_environment_variables(self, default_environment_variables: Dict[str, str] = None):
if default_environment_variables is None:
return
for key, value in default_environment_variables.items():
if key not in os.environ:
os.environ[key] = value
def add_default_routes(app: PromptflowServingApp):
@app.errorhandler(Exception)
def handle_error(e):
err_resp, resp_code = handle_error_to_response(e, logger)
app.flow_monitor.handle_error(e, resp_code)
return err_resp, resp_code
@app.route("/score", methods=["POST"])
@enable_monitoring
def score():
"""process a flow request in the runtime."""
raw_data = request.get_data()
logger.debug(f"PromptFlow executor received data: {raw_data}")
app.init_invoker_if_not_exist()
if app.flow.inputs.keys().__len__() == 0:
data = {}
logger.info("Flow has no input, request data will be ignored.")
else:
logger.info("Start loading request data...")
data = load_request_data(app.flow, raw_data, logger)
# set context data
g.data = data
g.flow_id = app.flow.id or app.flow.name
run_id = g.get("req_id", None)
# TODO: refine this once we can directly set the input/output log level to DEBUG in flow_invoker.
disable_data_logging = logger.level >= logging.INFO
flow_result = app.flow_invoker.invoke(data, run_id=run_id, disable_input_output_logging=disable_data_logging)
g.flow_result = flow_result
# check flow result, if failed, return error response
if flow_result.run_info.status != Status.Completed:
if flow_result.run_info.error:
err = ErrorResponse(flow_result.run_info.error)
g.err_code = err.innermost_error_code
return jsonify(err.to_simplified_dict()), err.response_code
else:
# in case of run failed but can't find any error, return 500
exception = SystemErrorException("Flow execution failed without error message.")
return jsonify(ErrorResponse.from_exception(exception).to_simplified_dict()), 500
intermediate_output = flow_result.output or {}
# remove evaluation only fields
result_output = {k: v for k, v in intermediate_output.items() if k not in app.response_fields_to_remove}
response_creator = ResponseCreator(
flow_run_result=result_output,
accept_mimetypes=request.accept_mimetypes,
response_original_value=flow_result.response_original_value,
)
app.flow_monitor.setup_streaming_monitor_if_needed(response_creator, data, intermediate_output)
return response_creator.create_response()
@app.route("/swagger.json", methods=["GET"])
def swagger():
"""Get the swagger object."""
return jsonify(app.swagger)
@app.route("/health", methods=["GET"])
def health():
"""Check if the runtime is alive."""
return {"status": "Healthy", "version": VERSION}
@app.route("/version", methods=["GET"])
def version():
"""Check the runtime's version."""
build_info = os.environ.get("BUILD_INFO", "")
try:
build_info_dict = json.loads(build_info)
version = build_info_dict["build_number"]
except Exception:
version = VERSION
return {"status": "Healthy", "build_info": build_info, "version": version} | null |
4,135 | import json
import logging
import mimetypes
import os
from pathlib import Path
from typing import Dict
from flask import Flask, g, jsonify, request
from promptflow._sdk._load_functions import load_flow
from promptflow._sdk._serving.extension.extension_factory import ExtensionFactory
from promptflow._sdk._serving.flow_invoker import FlowInvoker
from promptflow._sdk._serving.response_creator import ResponseCreator
from promptflow._sdk._serving.utils import (
enable_monitoring,
get_output_fields_to_remove,
get_sample_json,
handle_error_to_response,
load_request_data,
streaming_response_required,
)
from promptflow._sdk._utils import setup_user_agent_to_operation_context
from promptflow._utils.exception_utils import ErrorResponse
from promptflow._utils.logger_utils import LoggerFactory
from promptflow._version import VERSION
from promptflow.contracts.run_info import Status
from promptflow.exceptions import SystemErrorException
from promptflow.storage._run_storage import DummyRunStorage
from .swagger import generate_swagger
logger = LoggerFactory.get_logger("pfserving-app", target_stdout=True)
class PromptflowServingApp(Flask):
def init(self, **kwargs):
with self.app_context():
# default to local, can be override when creating the app
self.extension = ExtensionFactory.create_extension(logger, **kwargs)
self.flow_invoker: FlowInvoker = None
# parse promptflow project path
self.project_path = self.extension.get_flow_project_path()
logger.info(f"Project path: {self.project_path}")
self.flow_entity = load_flow(self.project_path)
self.flow = self.flow_entity._init_executable()
# enable environment_variables
environment_variables = kwargs.get("environment_variables", {})
os.environ.update(environment_variables)
default_environment_variables = self.flow.get_environment_variables_with_overrides()
self.set_default_environment_variables(default_environment_variables)
# load trace exporters
trace_exporters = self.extension.get_trace_exporters(self.project_path)
if trace_exporters:
logger.info(f"Enable {len(trace_exporters)} trace exporters.")
from opentelemetry import trace
from opentelemetry.sdk.resources import SERVICE_NAME, Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
resource = Resource(
attributes={
SERVICE_NAME: "promptflow",
}
)
trace.set_tracer_provider(TracerProvider(resource=resource))
provider = trace.get_tracer_provider()
for exporter in trace_exporters:
provider.add_span_processor(BatchSpanProcessor(exporter))
self.flow_name = self.extension.get_flow_name()
self.flow.name = self.flow_name
conn_data_override, conn_name_override = self.extension.get_override_connections(self.flow)
self.connections_override = conn_data_override
self.connections_name_override = conn_name_override
self.flow_monitor = self.extension.get_flow_monitor()
self.connection_provider = self.extension.get_connection_provider()
self.credential = self.extension.get_credential()
self.sample = get_sample_json(self.project_path, logger)
self.init_swagger()
# try to initialize the flow invoker
try:
self.init_invoker_if_not_exist()
except Exception as e:
if self.extension.raise_ex_on_invoker_initialization_failure(e):
raise e
# ensure response has the correct content type
mimetypes.add_type("application/javascript", ".js")
mimetypes.add_type("text/css", ".css")
setup_user_agent_to_operation_context(self.extension.get_user_agent())
add_default_routes(self)
# register blueprints
blue_prints = self.extension.get_blueprints()
for blue_print in blue_prints:
self.register_blueprint(blue_print)
def init_invoker_if_not_exist(self):
if self.flow_invoker:
return
logger.info("Promptflow executor starts initializing...")
self.flow_invoker = FlowInvoker(
self.project_path,
connection_provider=self.connection_provider,
streaming=streaming_response_required,
raise_ex=False,
connections=self.connections_override,
connections_name_overrides=self.connections_name_override,
# for serving, we don't need to persist intermediate result, this is to avoid memory leak.
storage=DummyRunStorage(),
credential=self.credential,
)
self.flow = self.flow_invoker.flow
# Set the flow name as folder name
self.flow.name = self.flow_name
self.response_fields_to_remove = get_output_fields_to_remove(self.flow, logger)
logger.info("Promptflow executor initializing succeed!")
def init_swagger(self):
self.response_fields_to_remove = get_output_fields_to_remove(self.flow, logger)
self.swagger = generate_swagger(self.flow, self.sample, self.response_fields_to_remove)
def set_default_environment_variables(self, default_environment_variables: Dict[str, str] = None):
if default_environment_variables is None:
return
for key, value in default_environment_variables.items():
if key not in os.environ:
os.environ[key] = value
def create_app(**kwargs):
app = PromptflowServingApp(__name__)
if __name__ != "__main__":
app.logger.handlers = logger.handlers
app.logger.setLevel(logger.level)
app.init(**kwargs)
return app | null |
4,136 | import flask
from jinja2 import Template
from pathlib import Path
from flask import Blueprint, request, url_for, current_app as app
The provided code snippet includes necessary dependencies for implementing the `construct_staticweb_blueprint` function. Write a Python function `def construct_staticweb_blueprint(static_folder)` to solve the following problem:
Construct static web blueprint.
Here is the function:
def construct_staticweb_blueprint(static_folder):
"""Construct static web blueprint."""
staticweb_blueprint = Blueprint("staticweb_blueprint", __name__, static_folder=static_folder)
@staticweb_blueprint.route("/", methods=["GET", "POST"])
def home():
"""Show the home page."""
index_path = Path(static_folder) / "index.html" if static_folder else None
if index_path and index_path.exists():
template = Template(open(index_path, "r", encoding="UTF-8").read())
return flask.render_template(template, url_for=url_for)
else:
return "<h1>Welcome to promptflow app.</h1>"
@staticweb_blueprint.route("/<path:path>", methods=["GET", "POST", "PUT", "DELETE", "PATCH"])
def notfound(path):
rules = {rule.rule: rule.methods for rule in app.url_map.iter_rules()}
if path not in rules or request.method not in rules[path]:
unsupported_message = (
f"The requested api {path!r} with {request.method} is not supported by current app, "
f"if you entered the URL manually please check your spelling and try again."
)
return unsupported_message, 404
return staticweb_blueprint | Construct static web blueprint. |
4,137 | from flask import Blueprint, current_app as app, request
from promptflow._sdk._serving.monitor.flow_monitor import FlowMonitor
def is_monitoring_enabled() -> bool:
enabled = False
if request.endpoint in app.view_functions:
view_func = app.view_functions[request.endpoint]
enabled = hasattr(view_func, "_enable_monitoring")
return enabled
The provided code snippet includes necessary dependencies for implementing the `construct_monitor_blueprint` function. Write a Python function `def construct_monitor_blueprint(flow_monitor: FlowMonitor)` to solve the following problem:
Construct monitor blueprint.
Here is the function:
def construct_monitor_blueprint(flow_monitor: FlowMonitor):
"""Construct monitor blueprint."""
monitor_blueprint = Blueprint("monitor_blueprint", __name__)
@monitor_blueprint.before_app_request
def start_monitoring():
if not is_monitoring_enabled():
return
flow_monitor.start_monitoring()
@monitor_blueprint.after_app_request
def finish_monitoring(response):
if not is_monitoring_enabled():
return response
flow_monitor.finish_monitoring(response.status_code)
return response
return monitor_blueprint | Construct monitor blueprint. |
4,138 | import logging
from promptflow.contracts.flow import Flow, FlowInputDefinition, FlowOutputDefinition
from promptflow.contracts.tool import ValueType
def generate_input_field_schema(input: FlowInputDefinition) -> dict:
field_schema = {"type": type_mapping[input.type]}
if input.description:
field_schema["description"] = input.description
if input.default:
field_schema["default"] = input.default
if input.type == ValueType.OBJECT:
field_schema["additionalProperties"] = {}
if input.type == ValueType.LIST:
field_schema["items"] = {"type": "object", "additionalProperties": {}}
return field_schema
def generate_output_field_schema(output: FlowOutputDefinition) -> dict:
field_schema = {"type": type_mapping[output.type]}
if output.description:
field_schema["description"] = output.description
if output.type == ValueType.OBJECT:
field_schema["additionalProperties"] = {}
if output.type == ValueType.LIST:
field_schema["items"] = {"type": "object", "additionalProperties": {}}
return field_schema
The provided code snippet includes necessary dependencies for implementing the `generate_swagger` function. Write a Python function `def generate_swagger(flow: Flow, samples, outputs_to_remove: list) -> dict` to solve the following problem:
convert a flow to swagger object.
Here is the function:
def generate_swagger(flow: Flow, samples, outputs_to_remove: list) -> dict:
"""convert a flow to swagger object."""
swagger = {"openapi": "3.0.0"}
swagger["info"] = {
"title": f"Promptflow[{flow.name}] API",
"version": "1.0.0",
"x-flow-name": str(flow.name),
}
swagger["components"] = {
"securitySchemes": {
"bearerAuth": {
"type": "http",
"scheme": "bearer",
}
}
}
swagger["security"] = [{"bearerAuth": []}]
input_schema = {"type": "object"}
request_body_required = False
if len(flow.inputs) > 0:
input_schema["properties"] = {}
input_schema["required"] = []
request_body_required = True
for name, input in flow.inputs.items():
if input.is_chat_input:
swagger["info"]["x-chat-input"] = name
swagger["info"]["x-flow-type"] = "chat"
if input.is_chat_history:
swagger["info"]["x-chat-history"] = name
input_schema["properties"][name] = generate_input_field_schema(input)
input_schema["required"].append(name)
output_schema = {"type": "object"}
if len(flow.outputs) > 0:
output_schema["properties"] = {}
for name, output in flow.outputs.items():
# skip evaluation only outputs in swagger
# TODO remove this if sdk removed this evaluation_only field
if output.evaluation_only:
continue
if output.is_chat_output:
swagger["info"]["x-chat-output"] = name
if outputs_to_remove and name in outputs_to_remove:
continue
output_schema["properties"][name] = generate_output_field_schema(output)
example = {}
if samples:
if isinstance(samples, list):
example = samples[0]
else:
logging.warning("samples should be a list of dict, but got %s, skipped.", type(samples))
swagger["paths"] = {
"/score": {
"post": {
"summary": f"run promptflow: {flow.name} with an given input",
"requestBody": {
"description": "promptflow input data",
"required": request_body_required,
"content": {
"application/json": {
"schema": input_schema,
"example": example, # need to check this based on the sample data
}
},
},
"responses": {
"200": {
"description": "successful operation",
"content": {
"application/json": {
"schema": output_schema,
}
},
},
"400": {
"description": "Invalid input",
},
"default": {
"description": "unexpected error",
},
},
}
}
}
return swagger | convert a flow to swagger object. |
4,139 | import time
from functools import partial, wraps
from typing import Tuple, Union
from sqlalchemy.exc import OperationalError
The provided code snippet includes necessary dependencies for implementing the `retry` function. Write a Python function `def retry(exception_to_check: Union[Exception, Tuple[Exception]], tries=4, delay=3, backoff=2, logger=None)` 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[Exception, Tuple[Exception]], tries=4, delay=3, backoff=2, logger=None):
"""
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:
if logger:
logger.info("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
if logger:
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,140 | import datetime
import os
from contextlib import contextmanager
from pathlib import Path
from typing import List, Union
from filelock import FileLock
from sqlalchemy import create_engine, event, inspect, text
from sqlalchemy.exc import OperationalError
from sqlalchemy.orm import Session, sessionmaker
from sqlalchemy.schema import CreateTable
from promptflow._sdk._configuration import Configuration
from promptflow._sdk._constants import (
CONNECTION_TABLE_NAME,
EXP_NODE_RUN_TABLE_NAME,
EXPERIMENT_CREATED_ON_INDEX_NAME,
EXPERIMENT_TABLE_NAME,
LOCAL_MGMT_DB_PATH,
LOCAL_MGMT_DB_SESSION_ACQUIRE_LOCK_PATH,
ORCHESTRATOR_TABLE_NAME,
RUN_INFO_CREATED_ON_INDEX_NAME,
RUN_INFO_TABLENAME,
SCHEMA_INFO_TABLENAME,
SPAN_TABLENAME,
TRACE_MGMT_DB_PATH,
TRACE_MGMT_DB_SESSION_ACQUIRE_LOCK_PATH,
)
from promptflow._sdk._utils import (
get_promptflow_sdk_version,
print_red_error,
print_yellow_warning,
use_customized_encryption_key,
)
session_maker = None
lock = FileLock(LOCAL_MGMT_DB_SESSION_ACQUIRE_LOCK_PATH)
def support_transaction(engine):
# workaround to make SQLite support transaction; reference to SQLAlchemy doc:
# https://docs.sqlalchemy.org/en/20/dialects/sqlite.html#serializable-isolation-savepoints-transactional-ddl
def do_connect(db_api_connection, connection_record):
# disable pysqlite emitting of the BEGIN statement entirely.
# also stops it from emitting COMMIT before any DDL.
db_api_connection.isolation_level = None
def do_begin(conn):
# emit our own BEGIN
conn.exec_driver_sql("BEGIN")
return engine
def create_or_update_table(engine, orm_class, tablename: str) -> None:
# create schema_info table if not exists
sql = f"CREATE TABLE IF NOT EXISTS {SCHEMA_INFO_TABLENAME} (tablename TEXT PRIMARY KEY, version TEXT NOT NULL);"
with engine.begin() as connection:
connection.execute(text(sql))
# no table in database yet
# create table via ORM class and update schema info
if not inspect(engine).has_table(tablename):
orm_class.metadata.create_all(engine)
update_current_schema(engine, orm_class, tablename)
return
db_schema_version = get_db_schema_version(engine, tablename)
sdk_schema_version = int(orm_class.__pf_schema_version__)
# same schema, no action needed
if db_schema_version == sdk_schema_version:
return
elif db_schema_version > sdk_schema_version:
# schema in database is later than SDK schema
# though different, we have design principal that later schema will always have no less columns
# while new columns should be nullable or with default value
# so that older schema can always use existing schema
# we print warning message but not do other action
warning_message = (
f"We have noticed that you are using an older SDK version: {get_promptflow_sdk_version()!r}.\n"
"While we will do our best to ensure compatibility, "
"we highly recommend upgrading to the latest version of SDK for the best experience."
)
print_yellow_warning(warning_message)
return
else:
# schema in database is older than SDK schema
# so we have to create table with new schema
# in this case, we need to:
# 1. rename existing table name
# 2. create table with current schema
# 3. copy data from renamed table to new table
legacy_tablename = generate_legacy_tablename(engine, tablename)
rename_sql = f"ALTER TABLE {tablename} RENAME TO {legacy_tablename};"
create_table_sql = str(CreateTable(orm_class.__table__).compile(engine))
copy_sql = build_copy_sql(
old_name=legacy_tablename,
new_name=tablename,
old_columns=[column["name"] for column in inspect(engine).get_columns(tablename)],
new_columns=[column.name for column in orm_class.__table__.columns],
)
# note that we should do above in one transaction
with engine.begin() as connection:
connection.execute(text(rename_sql))
connection.execute(text(create_table_sql))
connection.execute(text(copy_sql))
# update schema info finally
update_current_schema(engine, orm_class, tablename)
return
def create_table_if_not_exists(engine, table_name, orm_class) -> None:
if inspect(engine).has_table(table_name):
return
try:
if inspect(engine).has_table(table_name):
return
orm_class.metadata.create_all(engine)
except OperationalError as e:
# only ignore error if table already exists
expected_error_message = f"table {table_name} already exists"
if expected_error_message not in str(e):
raise
def create_index_if_not_exists(engine, index_name, table_name, col_name) -> None:
# created_on
sql = f"CREATE INDEX IF NOT EXISTS {index_name} ON {table_name} (f{col_name});"
with engine.begin() as connection:
connection.execute(text(sql))
return
def mgmt_db_session() -> Session:
global session_maker
global lock
if session_maker is not None:
return session_maker()
lock.acquire()
try: # try-finally to always release lock
if session_maker is not None:
return session_maker()
if not LOCAL_MGMT_DB_PATH.parent.is_dir():
LOCAL_MGMT_DB_PATH.parent.mkdir(parents=True, exist_ok=True)
engine = create_engine(f"sqlite:///{str(LOCAL_MGMT_DB_PATH)}?check_same_thread=False", future=True)
engine = support_transaction(engine)
from promptflow._sdk._orm import Connection, Experiment, ExperimentNodeRun, Orchestrator, RunInfo
create_or_update_table(engine, orm_class=RunInfo, tablename=RUN_INFO_TABLENAME)
create_table_if_not_exists(engine, CONNECTION_TABLE_NAME, Connection)
create_table_if_not_exists(engine, ORCHESTRATOR_TABLE_NAME, Orchestrator)
create_table_if_not_exists(engine, EXP_NODE_RUN_TABLE_NAME, ExperimentNodeRun)
create_index_if_not_exists(engine, RUN_INFO_CREATED_ON_INDEX_NAME, RUN_INFO_TABLENAME, "created_on")
if Configuration.get_instance().is_internal_features_enabled():
create_or_update_table(engine, orm_class=Experiment, tablename=EXPERIMENT_TABLE_NAME)
create_index_if_not_exists(engine, EXPERIMENT_CREATED_ON_INDEX_NAME, EXPERIMENT_TABLE_NAME, "created_on")
session_maker = sessionmaker(bind=engine)
except Exception as e: # pylint: disable=broad-except
# if we cannot manage to create the connection to the management database
# we can barely do nothing but raise the exception with printing the error message
error_message = f"Failed to create management database: {str(e)}"
print_red_error(error_message)
raise
finally:
lock.release()
return session_maker() | null |
4,141 | import datetime
import os
from contextlib import contextmanager
from pathlib import Path
from typing import List, Union
from filelock import FileLock
from sqlalchemy import create_engine, event, inspect, text
from sqlalchemy.exc import OperationalError
from sqlalchemy.orm import Session, sessionmaker
from sqlalchemy.schema import CreateTable
from promptflow._sdk._configuration import Configuration
from promptflow._sdk._constants import (
CONNECTION_TABLE_NAME,
EXP_NODE_RUN_TABLE_NAME,
EXPERIMENT_CREATED_ON_INDEX_NAME,
EXPERIMENT_TABLE_NAME,
LOCAL_MGMT_DB_PATH,
LOCAL_MGMT_DB_SESSION_ACQUIRE_LOCK_PATH,
ORCHESTRATOR_TABLE_NAME,
RUN_INFO_CREATED_ON_INDEX_NAME,
RUN_INFO_TABLENAME,
SCHEMA_INFO_TABLENAME,
SPAN_TABLENAME,
TRACE_MGMT_DB_PATH,
TRACE_MGMT_DB_SESSION_ACQUIRE_LOCK_PATH,
)
from promptflow._sdk._utils import (
get_promptflow_sdk_version,
print_red_error,
print_yellow_warning,
use_customized_encryption_key,
)
os.environ["SQLALCHEMY_SILENCE_UBER_WARNING"] = "1"
session_maker = None
The provided code snippet includes necessary dependencies for implementing the `mgmt_db_rebase` function. Write a Python function `def mgmt_db_rebase(mgmt_db_path: Union[Path, os.PathLike, str], customized_encryption_key: str = None) -> Session` to solve the following problem:
This function will change the constant LOCAL_MGMT_DB_PATH to the new path so very dangerous. It is created for pf flow export only and need to be removed in further version.
Here is the function:
def mgmt_db_rebase(mgmt_db_path: Union[Path, os.PathLike, str], customized_encryption_key: str = None) -> Session:
"""
This function will change the constant LOCAL_MGMT_DB_PATH to the new path so very dangerous.
It is created for pf flow export only and need to be removed in further version.
"""
global session_maker
global LOCAL_MGMT_DB_PATH
origin_local_db_path = LOCAL_MGMT_DB_PATH
LOCAL_MGMT_DB_PATH = mgmt_db_path
session_maker = None
if customized_encryption_key:
with use_customized_encryption_key(customized_encryption_key):
yield
else:
yield
LOCAL_MGMT_DB_PATH = origin_local_db_path
session_maker = None | This function will change the constant LOCAL_MGMT_DB_PATH to the new path so very dangerous. It is created for pf flow export only and need to be removed in further version. |
4,142 | import datetime
import os
from contextlib import contextmanager
from pathlib import Path
from typing import List, Union
from filelock import FileLock
from sqlalchemy import create_engine, event, inspect, text
from sqlalchemy.exc import OperationalError
from sqlalchemy.orm import Session, sessionmaker
from sqlalchemy.schema import CreateTable
from promptflow._sdk._configuration import Configuration
from promptflow._sdk._constants import (
CONNECTION_TABLE_NAME,
EXP_NODE_RUN_TABLE_NAME,
EXPERIMENT_CREATED_ON_INDEX_NAME,
EXPERIMENT_TABLE_NAME,
LOCAL_MGMT_DB_PATH,
LOCAL_MGMT_DB_SESSION_ACQUIRE_LOCK_PATH,
ORCHESTRATOR_TABLE_NAME,
RUN_INFO_CREATED_ON_INDEX_NAME,
RUN_INFO_TABLENAME,
SCHEMA_INFO_TABLENAME,
SPAN_TABLENAME,
TRACE_MGMT_DB_PATH,
TRACE_MGMT_DB_SESSION_ACQUIRE_LOCK_PATH,
)
from promptflow._sdk._utils import (
get_promptflow_sdk_version,
print_red_error,
print_yellow_warning,
use_customized_encryption_key,
)
trace_session_maker = None
trace_lock = FileLock(TRACE_MGMT_DB_SESSION_ACQUIRE_LOCK_PATH)
def support_transaction(engine):
# workaround to make SQLite support transaction; reference to SQLAlchemy doc:
# https://docs.sqlalchemy.org/en/20/dialects/sqlite.html#serializable-isolation-savepoints-transactional-ddl
def do_connect(db_api_connection, connection_record):
# disable pysqlite emitting of the BEGIN statement entirely.
# also stops it from emitting COMMIT before any DDL.
db_api_connection.isolation_level = None
def do_begin(conn):
# emit our own BEGIN
conn.exec_driver_sql("BEGIN")
return engine
def trace_mgmt_db_session() -> Session:
global trace_session_maker
global trace_lock
if trace_session_maker is not None:
return trace_session_maker()
trace_lock.acquire()
try:
if trace_session_maker is not None:
return trace_session_maker()
if not TRACE_MGMT_DB_PATH.parent.is_dir():
TRACE_MGMT_DB_PATH.parent.mkdir(parents=True, exist_ok=True)
engine = create_engine(f"sqlite:///{str(TRACE_MGMT_DB_PATH)}", future=True)
engine = support_transaction(engine)
if not inspect(engine).has_table(SPAN_TABLENAME):
from promptflow._sdk._orm.trace import Span
Span.metadata.create_all(engine)
trace_session_maker = sessionmaker(bind=engine)
except Exception as e: # pylint: disable=broad-except
# if we cannot manage to create the connection to the OpenTelemetry management database
# we can barely do nothing but raise the exception with printing the error message
error_message = f"Failed to create OpenTelemetry management database: {str(e)}"
print_red_error(error_message)
raise
finally:
trace_lock.release()
return trace_session_maker() | null |
4,143 | from os import PathLike
from typing import IO, AnyStr, Union
from promptflow._sdk._load_functions import load_run
from promptflow._sdk._pf_client import PFClient
from promptflow._sdk.entities._run import Run
def _resume_run(**kwargs):
client = PFClient()
# Pass through kwargs to run to ensure all params supported.
return client.run(**kwargs) | null |
4,144 | from os import PathLike
from typing import IO, AnyStr, Union
from promptflow._sdk._load_functions import load_run
from promptflow._sdk._pf_client import PFClient
from promptflow._sdk.entities._run import Run
def _create_run(run: Run, **kwargs):
client = PFClient()
return client.runs.create_or_update(run=run, **kwargs)
The provided code snippet includes necessary dependencies for implementing the `create_yaml_run` function. Write a Python function `def create_yaml_run(source: Union[str, PathLike, IO[AnyStr]], params_override: list = None, **kwargs)` to solve the following problem:
Create a run from a yaml file. Should only call from CLI.
Here is the function:
def create_yaml_run(source: Union[str, PathLike, IO[AnyStr]], params_override: list = None, **kwargs):
"""Create a run from a yaml file. Should only call from CLI."""
run = load_run(source, params_override=params_override, **kwargs)
return _create_run(run=run, **kwargs) | Create a run from a yaml file. Should only call from CLI. |
4,145 | import os
from collections import namedtuple
from enum import Enum
from pathlib import Path
from promptflow._constants import (
CONNECTION_SCRUBBED_VALUE,
ConnectionAuthMode,
ConnectionType,
CustomStrongTypeConnectionConfigs,
)
PROMPT_FLOW_HOME_DIR_ENV_VAR = "PF_HOME_DIRECTORY"
PROMPT_FLOW_DIR_NAME = ".promptflow"
HOME_PROMPT_FLOW_DIR = _prepare_home_dir()
The provided code snippet includes necessary dependencies for implementing the `_prepare_home_dir` function. Write a Python function `def _prepare_home_dir() -> Path` to solve the following problem:
Prepare prompt flow home directory. User can configure it by setting environment variable: `PF_HOME_DIRECTORY`; if not configured, or configured value is not valid, use default value: "~/.promptflow/".
Here is the function:
def _prepare_home_dir() -> Path:
"""Prepare prompt flow home directory.
User can configure it by setting environment variable: `PF_HOME_DIRECTORY`;
if not configured, or configured value is not valid, use default value: "~/.promptflow/".
"""
from promptflow._utils.logger_utils import get_cli_sdk_logger
logger = get_cli_sdk_logger()
if PROMPT_FLOW_HOME_DIR_ENV_VAR in os.environ:
logger.debug(
f"environment variable {PROMPT_FLOW_HOME_DIR_ENV_VAR!r} is set, honor it preparing home directory."
)
try:
pf_home_dir = Path(os.getenv(PROMPT_FLOW_HOME_DIR_ENV_VAR)).resolve()
pf_home_dir.mkdir(parents=True, exist_ok=True)
return pf_home_dir
except Exception as e: # pylint: disable=broad-except
_warning_message = (
"Invalid configuration for prompt flow home directory: "
f"{os.getenv(PROMPT_FLOW_HOME_DIR_ENV_VAR)!r}: {str(e)!r}.\n"
'Fall back to use default value: "~/.promptflow/".'
)
logger.warning(_warning_message)
try:
logger.debug("preparing home directory with default value.")
pf_home_dir = (Path.home() / PROMPT_FLOW_DIR_NAME).resolve()
pf_home_dir.mkdir(parents=True, exist_ok=True)
return pf_home_dir
except Exception as e: # pylint: disable=broad-except
_error_message = (
f"Cannot create prompt flow home directory: {str(e)!r}.\n"
"Please check if you have proper permission to operate the directory "
f"{HOME_PROMPT_FLOW_DIR.as_posix()!r}; or configure it via "
f"environment variable {PROMPT_FLOW_HOME_DIR_ENV_VAR!r}.\n"
)
logger.error(_error_message)
raise Exception(_error_message) | Prepare prompt flow home directory. User can configure it by setting environment variable: `PF_HOME_DIRECTORY`; if not configured, or configured value is not valid, use default value: "~/.promptflow/". |
4,146 | import os
from collections import namedtuple
from enum import Enum
from pathlib import Path
from promptflow._constants import (
CONNECTION_SCRUBBED_VALUE,
ConnectionAuthMode,
ConnectionType,
CustomStrongTypeConnectionConfigs,
)
class ListViewType(str, Enum):
def get_list_view_type(archived_only: bool, include_archived: bool) -> ListViewType:
if archived_only and include_archived:
raise Exception("Cannot provide both archived-only and include-archived.")
if include_archived:
return ListViewType.ALL
elif archived_only:
return ListViewType.ARCHIVED_ONLY
else:
return ListViewType.ACTIVE_ONLY | null |
4,147 | import json
import os
import time
from copy import copy
from pathlib import Path
from types import GeneratorType
import streamlit as st
from PIL import Image
from streamlit_quill import st_quill
from utils import dict_iter_render_message, parse_image_content, parse_list_from_html, render_single_dict_message
from promptflow import load_flow
from promptflow._constants import STREAMING_ANIMATION_TIME
from promptflow._sdk._submitter.utils import resolve_generator, resolve_generator_output_with_cache
from promptflow._sdk._utils import dump_flow_result
from promptflow._utils.multimedia_utils import convert_multimedia_data_to_base64, persist_multimedia_data
invoker = None
def dict_iter_render_message(message_items):
if is_multimedia_dict(message_items):
key = list(message_items.keys())[0]
value = message_items[key]
show_image(value, key)
elif is_dict_contains_rich_text(message_items):
st.markdown("{ ")
for key, value in message_items.items():
if re.match(MIME_PATTERN, key):
show_image(value, key)
else:
if isinstance(value, list):
st.markdown(f"{key}: ")
list_iter_render_message(value)
elif isinstance(value, dict):
st.markdown(f"{key}: ")
dict_iter_render_message(value)
else:
item_render_message(value, key)
st.markdown("}, ")
else:
st.markdown(f"{json_dumps(message_items)},")
def render_single_dict_message(message_items):
# This function is added for chat flow with only single input and single output.
# So that we can show the message directly without the list and dict wrapper.
for key, value in message_items.items():
if re.match(MIME_PATTERN, key):
show_image(value, key)
continue
else:
if isinstance(value, list):
render_single_list_message(value)
elif isinstance(value, dict):
render_single_dict_message(value)
else:
item_render_message(value, key)
def parse_list_from_html(html_content):
"""
Parse the html content to a list of strings and images.
"""
soup = BeautifulSoup(html_content, "html.parser")
result = []
for p in soup.find_all("p"):
result.extend(extract_content(p))
return result
def parse_image_content(image_content, image_type):
if image_content is not None:
file_contents = image_content.read()
image_content = base64.b64encode(file_contents).decode("utf-8")
prefix = f"data:{image_type};base64"
return {prefix: image_content}
def start():
def clear_chat() -> None:
st.session_state.messages = []
def render_message(role, message_items):
with st.chat_message(role):
if is_chat_flow:
render_single_dict_message(message_items)
else:
dict_iter_render_message(message_items)
def show_conversation() -> None:
if "messages" not in st.session_state:
st.session_state.messages = []
st.session_state.history = []
if st.session_state.messages:
for role, message_items in st.session_state.messages:
render_message(role, message_items)
def get_chat_history_from_session():
if "history" in st.session_state:
return st.session_state.history
return []
def post_process_dump_result(response, session_state_history, *, generator_record):
response = resolve_generator(response, generator_record)
# Get base64 for multi modal object
resolved_outputs = {
k: convert_multimedia_data_to_base64(v, with_type=True, dict_type=True) for k, v in response.output.items()
}
st.session_state.messages.append(("assistant", resolved_outputs))
session_state_history.update({"outputs": response.output})
st.session_state.history.append(session_state_history)
if is_chat_flow:
dump_path = Path(flow_path).parent
response.output = persist_multimedia_data(
response.output, base_dir=dump_path, sub_dir=Path(".promptflow/output")
)
dump_flow_result(flow_folder=dump_path, flow_result=response, prefix="chat")
return resolved_outputs
def submit(**kwargs) -> None:
# generator record should be reset for each submit
generator_record = {}
st.session_state.messages.append(("user", kwargs))
session_state_history = dict()
session_state_history.update({"inputs": kwargs})
with container:
render_message("user", kwargs)
# Force append chat history to kwargs
if is_chat_flow:
response = run_flow({chat_history_input_name: get_chat_history_from_session(), **kwargs})
else:
response = run_flow(kwargs)
if response.run_info.status.value == "Failed":
raise Exception(response.run_info.error)
if is_streaming:
# Display assistant response in chat message container
with container:
with st.chat_message("assistant"):
message_placeholder = st.empty()
full_response = f"{chat_output_name}: "
prefix_length = len(full_response)
chat_output = response.output[chat_output_name]
if isinstance(chat_output, GeneratorType):
# Simulate stream of response with milliseconds delay
for chunk in resolve_generator_output_with_cache(
chat_output, generator_record, generator_key=f"run.outputs.{chat_output_name}"
):
# there should be no extra spaces between adjacent chunks?
full_response += chunk
time.sleep(STREAMING_ANIMATION_TIME)
# Add a blinking cursor to simulate typing
message_placeholder.markdown(full_response + "▌")
message_placeholder.markdown(full_response)
response.output[chat_output_name] = full_response[prefix_length:]
post_process_dump_result(response, session_state_history, generator_record=generator_record)
return
resolved_outputs = post_process_dump_result(response, session_state_history, generator_record=generator_record)
with container:
render_message("assistant", resolved_outputs)
def run_flow(data: dict) -> dict:
global invoker
if not invoker:
if flow_path:
flow = Path(flow_path)
else:
flow = Path(__file__).parent / "flow"
if flow.is_dir():
os.chdir(flow)
else:
os.chdir(flow.parent)
invoker = load_flow(flow)
invoker.context.streaming = is_streaming
result = invoker.invoke(data)
return result
image = Image.open(Path(__file__).parent / "logo.png")
st.set_page_config(
layout="wide",
page_title=f"{flow_name} - Promptflow App",
page_icon=image,
menu_items={
"About": """
# This is a Promptflow App.
You can refer to [promptflow](https://github.com/microsoft/promptflow) for more information.
"""
},
)
# Set primary button color here since button color of the same form need to be identical in streamlit, but we only
# need Run/Chat button to be blue.
st.config.set_option("theme.primaryColor", "#0F6CBD")
st.title(flow_name)
st.divider()
st.chat_message("assistant").write("Hello, please input following flow inputs.")
container = st.container()
with container:
show_conversation()
with st.form(key="input_form", clear_on_submit=True):
settings_path = os.path.join(os.path.dirname(__file__), "settings.json")
if os.path.exists(settings_path):
with open(settings_path, "r", encoding="utf-8") as file:
json_data = json.load(file)
environment_variables = list(json_data.keys())
for environment_variable in environment_variables:
secret_input = st.sidebar.text_input(
label=environment_variable,
type="password",
placeholder=f"Please input {environment_variable} here. "
f"If you input before, you can leave it blank.",
)
if secret_input != "":
os.environ[environment_variable] = secret_input
flow_inputs_params = {}
for flow_input, (default_value, value_type) in flow_inputs.items():
if value_type == "list":
st.text(flow_input)
input = st_quill(
html=True,
toolbar=["image"],
key=flow_input,
placeholder="Please enter the list values and use the image icon to upload a picture. "
"Make sure to format each list item correctly with line breaks",
)
elif value_type == "image":
input = st.file_uploader(label=flow_input)
elif value_type == "string":
input = st.text_input(label=flow_input, placeholder=default_value)
else:
input = st.text_input(label=flow_input, placeholder=default_value)
flow_inputs_params.update({flow_input: copy(input)})
cols = st.columns(7)
submit_bt = cols[0].form_submit_button(label=label, type="primary")
clear_bt = cols[1].form_submit_button(label="Clear")
if submit_bt:
with st.spinner("Loading..."):
for flow_input, (default_value, value_type) in flow_inputs.items():
if value_type == "list":
input = parse_list_from_html(flow_inputs_params[flow_input])
flow_inputs_params.update({flow_input: copy(input)})
elif value_type == "image":
input = parse_image_content(
flow_inputs_params[flow_input],
flow_inputs_params[flow_input].type if flow_inputs_params[flow_input] else None,
)
flow_inputs_params.update({flow_input: copy(input)})
submit(**flow_inputs_params)
if clear_bt:
with st.spinner("Cleaning..."):
clear_chat()
st.rerun() | null |
4,148 | import os
import sys
from main import start
from streamlit.runtime import exists
from streamlit.web import cli as st_cli
from promptflow._cli._pf._connection import create_connection
def is_yaml_file(file_path):
# Get the file extension
_, file_extension = os.path.splitext(file_path)
# Check if the file extension is ".yaml" or ".yml"
return file_extension.lower() in (".yaml", ".yml")
def create_connections(directory_path) -> None:
for root, dirs, files in os.walk(directory_path):
for file in files:
file_path = os.path.join(root, file)
if is_yaml_file(file_path):
create_connection(file_path) | null |
4,149 | import os
from os import PathLike
from pathlib import Path
from typing import Any, Dict, List, Union
from .._constants import USER_AGENT_OVERRIDE_KEY
from .._utils.logger_utils import get_cli_sdk_logger
from ..exceptions import ErrorTarget, UserErrorException
from ._configuration import Configuration
from ._constants import MAX_SHOW_DETAILS_RESULTS, ConnectionProvider
from ._load_functions import load_flow
from ._user_agent import USER_AGENT
from ._utils import ClientUserAgentUtil, setup_user_agent_to_operation_context
from .entities import Run
from .entities._eager_flow import EagerFlow
from .operations import RunOperations
from .operations._connection_operations import ConnectionOperations
from .operations._experiment_operations import ExperimentOperations
from .operations._flow_operations import FlowOperations
from .operations._tool_operations import ToolOperations
from .operations._trace_operations import TraceOperations
class PFClient:
"""A client class to interact with prompt flow entities."""
def __init__(self, **kwargs):
logger.debug("PFClient init with kwargs: %s", kwargs)
# when this is set, telemetry from this client will use this user agent and ignore the one from OperationContext
self._user_agent_override = kwargs.pop(USER_AGENT_OVERRIDE_KEY, None)
self._connection_provider = kwargs.pop("connection_provider", None)
self._config = kwargs.get("config", None) or {}
# The credential is used as an option to override
# DefaultAzureCredential when using workspace connection provider
self._credential = kwargs.get("credential", None)
# user_agent_override will be applied to all TelemetryMixin operations
self._runs = RunOperations(self, user_agent_override=self._user_agent_override)
self._flows = FlowOperations(client=self, user_agent_override=self._user_agent_override)
self._experiments = ExperimentOperations(self, user_agent_override=self._user_agent_override)
# Lazy init to avoid azure credential requires too early
self._connections = None
self._tools = ToolOperations()
# add user agent from kwargs if any
if isinstance(kwargs.get("user_agent"), str):
ClientUserAgentUtil.append_user_agent(kwargs["user_agent"])
self._traces = TraceOperations()
setup_user_agent_to_operation_context(USER_AGENT)
def run(
self,
flow: Union[str, PathLike] = None,
*,
data: Union[str, PathLike] = None,
run: Union[str, Run] = None,
column_mapping: dict = None,
variant: str = None,
connections: dict = None,
environment_variables: dict = None,
name: str = None,
display_name: str = None,
tags: Dict[str, str] = None,
resume_from: Union[str, Run] = None,
**kwargs,
) -> Run:
"""Run flow against provided data or run.
.. note::
At least one of the ``data`` or ``run`` parameters must be provided.
.. admonition:: Column_mapping
Column mapping is a mapping from flow input name to specified values.
If specified, the flow will be executed with provided value for specified inputs.
The value can be:
- from data:
- ``data.col1``
- from run:
- ``run.inputs.col1``: if need reference run's inputs
- ``run.output.col1``: if need reference run's outputs
- Example:
- ``{"ground_truth": "${data.answer}", "prediction": "${run.outputs.answer}"}``
:param flow: Path to the flow directory to run evaluation.
:type flow: Union[str, PathLike]
:param data: Pointer to the test data (of variant bulk runs) for eval runs.
:type data: Union[str, PathLike]
:param run: Flow run ID or flow run. This parameter helps keep lineage between
the current run and variant runs. Batch outputs can be
referenced as ``${run.outputs.col_name}`` in inputs_mapping.
:type run: Union[str, ~promptflow.entities.Run]
:param column_mapping: Define a data flow logic to map input data.
:type column_mapping: Dict[str, str]
:param variant: Node & variant name in the format of ``${node_name.variant_name}``.
The default variant will be used if not specified.
:type variant: str
:param connections: Overwrite node level connections with provided values.
Example: ``{"node1": {"connection": "new_connection", "deployment_name": "gpt-35-turbo"}}``
:type connections: Dict[str, Dict[str, str]]
:param environment_variables: Environment variables to set by specifying a property path and value.
Example: ``{"key1": "${my_connection.api_key}", "key2"="value2"}``
The value reference to connection keys will be resolved to the actual value,
and all environment variables specified will be set into os.environ.
:type environment_variables: Dict[str, str]
:param name: Name of the run.
:type name: str
:param display_name: Display name of the run.
:type display_name: str
:param tags: Tags of the run.
:type tags: Dict[str, str]
:param resume_from: Create run resume from an existing run.
:type resume_from: str
:return: Flow run info.
:rtype: ~promptflow.entities.Run
"""
if resume_from:
unsupported = {
k: v
for k, v in {
"flow": flow,
"data": data,
"run": run,
"column_mapping": column_mapping,
"variant": variant,
"connections": connections,
"environment_variables": environment_variables,
}.items()
if v
}
if any(unsupported):
raise ValueError(
f"'resume_from' is not supported to be used with the with following parameters: {unsupported}. "
)
resume_from = resume_from.name if isinstance(resume_from, Run) else resume_from
return self.runs._create_by_resume_from(
resume_from=resume_from, name=name, display_name=display_name, tags=tags, **kwargs
)
if not flow:
raise ValueError("'flow' is required to create a run.")
if not os.path.exists(flow):
raise FileNotFoundError(f"flow path {flow} does not exist")
if data and not os.path.exists(data):
raise FileNotFoundError(f"data path {data} does not exist")
if not run and not data:
raise ValueError("at least one of data or run must be provided")
# load flow object for validation and early failure
flow_obj = load_flow(source=flow)
# validate param conflicts
if isinstance(flow_obj, EagerFlow):
if variant or connections:
logger.warning("variant and connections are not supported for eager flow, will be ignored")
variant, connections = None, None
run = Run(
name=name,
display_name=display_name,
tags=tags,
data=data,
column_mapping=column_mapping,
run=run,
variant=variant,
flow=Path(flow),
connections=connections,
environment_variables=environment_variables,
config=Configuration(overrides=self._config),
)
return self.runs.create_or_update(run=run, **kwargs)
def stream(self, run: Union[str, Run], raise_on_error: bool = True) -> Run:
"""Stream run logs to the console.
:param run: Run object or name of the run.
:type run: Union[str, ~promptflow.sdk.entities.Run]
:param raise_on_error: Raises an exception if a run fails or canceled.
:type raise_on_error: bool
:return: flow run info.
:rtype: ~promptflow.sdk.entities.Run
"""
return self.runs.stream(run, raise_on_error)
def get_details(
self, run: Union[str, Run], max_results: int = MAX_SHOW_DETAILS_RESULTS, all_results: bool = False
) -> "DataFrame":
"""Get the details from the run including inputs and outputs.
.. note::
If `all_results` is set to True, `max_results` will be overwritten to sys.maxsize.
:param run: The run name or run object
:type run: Union[str, ~promptflow.sdk.entities.Run]
:param max_results: The max number of runs to return, defaults to 100
:type max_results: int
:param all_results: Whether to return all results, defaults to False
:type all_results: bool
:raises RunOperationParameterError: If `max_results` is not a positive integer.
:return: The details data frame.
:rtype: pandas.DataFrame
"""
return self.runs.get_details(name=run, max_results=max_results, all_results=all_results)
def get_metrics(self, run: Union[str, Run]) -> Dict[str, Any]:
"""Get run metrics.
:param run: Run object or name of the run.
:type run: Union[str, ~promptflow.sdk.entities.Run]
:return: Run metrics.
:rtype: Dict[str, Any]
"""
return self.runs.get_metrics(run)
def visualize(self, runs: Union[List[str], List[Run]]) -> None:
"""Visualize run(s).
:param run: Run object or name of the run.
:type run: Union[str, ~promptflow.sdk.entities.Run]
"""
self.runs.visualize(runs)
def runs(self) -> RunOperations:
"""Run operations that can manage runs."""
return self._runs
def tools(self) -> ToolOperations:
"""Tool operations that can manage tools."""
return self._tools
def _ensure_connection_provider(self) -> str:
if not self._connection_provider:
# Get a copy with config override instead of the config instance
self._connection_provider = Configuration(overrides=self._config).get_connection_provider()
logger.debug("PFClient connection provider: %s", self._connection_provider)
return self._connection_provider
def connections(self) -> ConnectionOperations:
"""Connection operations that can manage connections."""
if not self._connections:
self._ensure_connection_provider()
self._connections = PFClient._build_connection_operation(
self._connection_provider,
self._credential,
user_agent_override=self._user_agent_override,
)
return self._connections
def _build_connection_operation(connection_provider: str, credential=None, **kwargs):
"""
Build a ConnectionOperation object based on connection provider.
:param connection_provider: Connection provider, e.g. local, azureml, azureml://subscriptions..., etc.
:type connection_provider: str
:param credential: Credential when remote provider, default to chained credential DefaultAzureCredential.
:type credential: object
"""
if connection_provider == ConnectionProvider.LOCAL.value:
from promptflow._sdk.operations._connection_operations import ConnectionOperations
logger.debug("PFClient using local connection operations.")
connection_operation = ConnectionOperations(**kwargs)
elif connection_provider.startswith(ConnectionProvider.AZUREML.value):
from promptflow._sdk.operations._local_azure_connection_operations import LocalAzureConnectionOperations
logger.debug(f"PFClient using local azure connection operations with credential {credential}.")
connection_operation = LocalAzureConnectionOperations(connection_provider, credential=credential, **kwargs)
else:
raise UserErrorException(
target=ErrorTarget.CONTROL_PLANE_SDK,
message_format="Unsupported connection provider: {connection_provider}",
connection_provider=connection_provider,
)
return connection_operation
def flows(self) -> FlowOperations:
"""Operations on the flow that can manage flows."""
return self._flows
def test(
self,
flow: Union[str, PathLike],
*,
inputs: dict = None,
variant: str = None,
node: str = None,
environment_variables: dict = None,
) -> dict:
"""Test flow or node.
:param flow: path to flow directory to test
:type flow: Union[str, PathLike]
:param inputs: Input data for the flow test
:type inputs: dict
:param variant: Node & variant name in format of ${node_name.variant_name}, will use default variant
if not specified.
:type variant: str
:param node: If specified it will only test this node, else it will test the flow.
:type node: str
:param environment_variables: Environment variables to set by specifying a property path and value.
Example: {"key1": "${my_connection.api_key}", "key2"="value2"}
The value reference to connection keys will be resolved to the actual value,
and all environment variables specified will be set into os.environ.
:type environment_variables: dict
:return: The result of flow or node
:rtype: dict
"""
return self.flows.test(
flow=flow, inputs=inputs, variant=variant, environment_variables=environment_variables, node=node
)
def _create_run(run: Run, **kwargs):
client = PFClient()
return client.runs.create_or_update(run=run, **kwargs) | null |
4,150 | import os.path
from dotenv import dotenv_values
from marshmallow import RAISE, fields, post_load, pre_load
from promptflow._sdk._constants import IdentityKeys
from promptflow._sdk._utils import is_remote_uri
from promptflow._sdk.schemas._base import PatchedSchemaMeta, YamlFileSchema
from promptflow._sdk.schemas._fields import LocalPathField, NestedField, StringTransformedEnum, UnionField
from promptflow._utils.logger_utils import get_cli_sdk_logger
The provided code snippet includes necessary dependencies for implementing the `_resolve_dot_env_file` function. Write a Python function `def _resolve_dot_env_file(data, **kwargs)` to solve the following problem:
Resolve .env file to environment variables.
Here is the function:
def _resolve_dot_env_file(data, **kwargs):
"""Resolve .env file to environment variables."""
env_var = data.get("environment_variables", None)
try:
if env_var and os.path.exists(env_var):
env_dict = dotenv_values(env_var)
data["environment_variables"] = env_dict
except TypeError:
pass
return data | Resolve .env file to environment variables. |
4,151 | import copy
import typing
from pathlib import Path
from marshmallow import fields
from marshmallow.exceptions import FieldInstanceResolutionError, ValidationError
from marshmallow.fields import _T, Field, Nested
from marshmallow.utils import RAISE, resolve_field_instance
from promptflow._sdk._constants import BASE_PATH_CONTEXT_KEY
from promptflow._sdk.schemas._base import PathAwareSchema
from promptflow._utils.logger_utils import LoggerFactory
class UnionField(fields.Field):
def __init__(self, union_fields: typing.List[fields.Field], is_strict=False, **kwargs):
super().__init__(**kwargs)
try:
# add the validation and make sure union_fields must be subclasses or instances of
# marshmallow.base.FieldABC
self._union_fields = [resolve_field_instance(cls_or_instance) for cls_or_instance in union_fields]
# TODO: make serialization/de-serialization work in the same way as json schema when is_strict is True
self.is_strict = is_strict # S\When True, combine fields with oneOf instead of anyOf at schema generation
except FieldInstanceResolutionError as error:
raise ValueError(
'Elements of "union_fields" must be subclasses or ' "instances of marshmallow.base.FieldABC."
) from error
def union_fields(self):
return iter(self._union_fields)
def insert_union_field(self, field):
self._union_fields.insert(0, field)
# This sets the parent for the schema and also handles nesting.
def _bind_to_schema(self, field_name, schema):
super()._bind_to_schema(field_name, schema)
self._union_fields = self._create_bind_fields(self._union_fields, field_name)
def _create_bind_fields(self, _fields, field_name):
new_union_fields = []
for field in _fields:
field = copy.deepcopy(field)
field._bind_to_schema(field_name, self)
new_union_fields.append(field)
return new_union_fields
def _serialize(self, value, attr, obj, **kwargs):
if value is None:
return None
errors = []
for field in self._union_fields:
try:
return field._serialize(value, attr, obj, **kwargs)
except ValidationError as e:
errors.extend(e.messages)
except (TypeError, ValueError, AttributeError) as e:
errors.extend([str(e)])
raise ValidationError(message=errors, field_name=attr)
def _deserialize(self, value, attr, data, **kwargs):
errors = []
for schema in self._union_fields:
try:
return schema.deserialize(value, attr, data, **kwargs)
except ValidationError as e:
errors.append(e.normalized_messages())
except (FileNotFoundError, TypeError) as e:
errors.append([str(e)])
finally:
# Revert base path to original path when job schema fail to deserialize job. For example, when load
# parallel job with component file reference starting with FILE prefix, maybe first CommandSchema will
# load component yaml according to AnonymousCommandComponentSchema, and YamlFileSchema will update base
# path. When CommandSchema fail to load, then Parallelschema will load component yaml according to
# AnonymousParallelComponentSchema, but base path now is incorrect, and will raise path not found error
# when load component yaml file.
if (
hasattr(schema, "name")
and schema.name == "jobs"
and hasattr(schema, "schema")
and isinstance(schema.schema, PathAwareSchema)
):
# use old base path to recover original base path
schema.schema.context[BASE_PATH_CONTEXT_KEY] = schema.schema.old_base_path
# recover base path of parent schema
schema.context[BASE_PATH_CONTEXT_KEY] = schema.schema.context[BASE_PATH_CONTEXT_KEY]
raise ValidationError(errors, field_name=attr)
class DumpableIntegerField(fields.Integer):
"""An int field that cannot serialize other type of values to int if self.strict."""
def _serialize(self, value, attr, obj, **kwargs) -> typing.Optional[typing.Union[str, _T]]:
if self.strict and not isinstance(value, int):
# this implementation can serialize bool to bool
raise self.make_error("invalid", input=value)
return super()._serialize(value, attr, obj, **kwargs)
class DumpableFloatField(fields.Float):
"""A float field that cannot serialize other type of values to float if self.strict."""
def __init__(
self,
*,
strict: bool = False,
allow_nan: bool = False,
as_string: bool = False,
**kwargs,
):
self.strict = strict
super().__init__(allow_nan=allow_nan, as_string=as_string, **kwargs)
def _validated(self, value):
if self.strict and not isinstance(value, float):
raise self.make_error("invalid", input=value)
return super()._validated(value)
def _serialize(self, value, attr, obj, **kwargs) -> typing.Optional[typing.Union[str, _T]]:
return super()._serialize(self._validated(value), attr, obj, **kwargs)
The provided code snippet includes necessary dependencies for implementing the `PrimitiveValueField` function. Write a Python function `def PrimitiveValueField(**kwargs)` to solve the following problem:
Function to return a union field for primitive value. :return: The primitive value field :rtype: Field
Here is the function:
def PrimitiveValueField(**kwargs):
"""Function to return a union field for primitive value.
:return: The primitive value field
:rtype: Field
"""
return UnionField(
[
# Note: order matters here - to make sure value parsed correctly.
# By default, when strict is false, marshmallow downcasts float to int.
# Setting it to true will throw a validation error when loading a float to int.
# https://github.com/marshmallow-code/marshmallow/pull/755
# Use DumpableIntegerField to make sure there will be validation error when
# loading/dumping a float to int.
# note that this field can serialize bool instance but cannot deserialize bool instance.
DumpableIntegerField(strict=True),
# Use DumpableFloatField with strict of True to avoid '1'(str) serialized to 1.0(float)
DumpableFloatField(strict=True),
# put string schema after Int and Float to make sure they won't dump to string
fields.Str(),
# fields.Bool comes last since it'll parse anything non-falsy to True
fields.Bool(),
],
**kwargs,
) | Function to return a union field for primitive value. :return: The primitive value field :rtype: Field |
4,152 | import tempfile
import webbrowser
from dataclasses import asdict
from pathlib import Path
from typing import Optional
from promptflow._sdk._constants import VIS_HTML_TMPL
from promptflow._sdk._utils import render_jinja_template
from promptflow.contracts._run_management import VisualizationRender
def generate_html_string(data: dict) -> str:
visualization_render = VisualizationRender(data=data)
return render_jinja_template(VIS_HTML_TMPL, **asdict(visualization_render)) | null |
4,153 | import tempfile
import webbrowser
from dataclasses import asdict
from pathlib import Path
from typing import Optional
from promptflow._sdk._constants import VIS_HTML_TMPL
from promptflow._sdk._utils import render_jinja_template
from promptflow.contracts._run_management import VisualizationRender
def try_to_open_html(html_path: str) -> None:
print(f"The HTML file is generated at {str(Path(html_path).resolve().absolute())!r}.")
print("Trying to view the result in a web browser...")
web_browser_opened = False
web_browser_opened = webbrowser.open(f"file://{html_path}")
if not web_browser_opened:
print(
f"Failed to visualize from the web browser, the HTML file locates at {html_path!r}.\n"
"You can manually open it with your web browser, or try SDK to visualize it."
)
else:
print("Successfully visualized from the web browser.")
def dump_html(html_string: str, html_path: Optional[str] = None, open_html: bool = True) -> None:
if html_path is not None:
with open(html_path, "w") as f:
f.write(html_string)
else:
with tempfile.NamedTemporaryFile(prefix="pf-visualize-detail-", suffix=".html", delete=False) as f:
f.write(html_string.encode("utf-8"))
html_path = f.name
if open_html:
try_to_open_html(html_path) | null |
4,154 | import contextlib
import hashlib
import json
import os
import platform
import re
import subprocess
import tempfile
import time
from collections import defaultdict
from os import PathLike
from pathlib import Path
from time import sleep
from types import GeneratorType
from typing import Any, Dict, List
import psutil
import pydash
from dotenv import load_dotenv
from pydash import objects
from promptflow._constants import STREAMING_ANIMATION_TIME
from promptflow._sdk._constants import (
ALL_CONNECTION_TYPES,
DEFAULT_VAR_ID,
INPUTS,
NODE,
NODE_VARIANTS,
NODES,
SUPPORTED_CONNECTION_FIELDS,
USE_VARIANTS,
VARIANTS,
ConnectionFields,
)
from promptflow._sdk._errors import InvalidFlowError, RunOperationError
from promptflow._sdk._load_functions import load_flow
from promptflow._sdk._utils import (
_merge_local_code_and_additional_includes,
get_local_connections_from_executable,
get_used_connection_names_from_dict,
update_dict_value_with_connections,
)
from promptflow._sdk.entities._eager_flow import EagerFlow
from promptflow._sdk.entities._flow import Flow, ProtectedFlow
from promptflow._utils.context_utils import _change_working_dir
from promptflow._utils.flow_utils import dump_flow_dag, load_flow_dag
from promptflow._utils.logger_utils import FileHandler, get_cli_sdk_logger
from promptflow.contracts.flow import Flow as ExecutableFlow
def remove_additional_includes(flow_path: Path):
flow_path, flow_dag = load_flow_dag(flow_path=flow_path)
flow_dag.pop("additional_includes", None)
dump_flow_dag(flow_dag, flow_path) | null |
4,155 | import contextlib
import hashlib
import json
import os
import platform
import re
import subprocess
import tempfile
import time
from collections import defaultdict
from os import PathLike
from pathlib import Path
from time import sleep
from types import GeneratorType
from typing import Any, Dict, List
import psutil
import pydash
from dotenv import load_dotenv
from pydash import objects
from promptflow._constants import STREAMING_ANIMATION_TIME
from promptflow._sdk._constants import (
ALL_CONNECTION_TYPES,
DEFAULT_VAR_ID,
INPUTS,
NODE,
NODE_VARIANTS,
NODES,
SUPPORTED_CONNECTION_FIELDS,
USE_VARIANTS,
VARIANTS,
ConnectionFields,
)
from promptflow._sdk._errors import InvalidFlowError, RunOperationError
from promptflow._sdk._load_functions import load_flow
from promptflow._sdk._utils import (
_merge_local_code_and_additional_includes,
get_local_connections_from_executable,
get_used_connection_names_from_dict,
update_dict_value_with_connections,
)
from promptflow._sdk.entities._eager_flow import EagerFlow
from promptflow._sdk.entities._flow import Flow, ProtectedFlow
from promptflow._utils.context_utils import _change_working_dir
from promptflow._utils.flow_utils import dump_flow_dag, load_flow_dag
from promptflow._utils.logger_utils import FileHandler, get_cli_sdk_logger
from promptflow.contracts.flow import Flow as ExecutableFlow
def overwrite_variant(flow_dag: dict, tuning_node: str = None, variant: str = None, drop_node_variants: bool = False):
# need to overwrite default variant if tuning node and variant not specified.
# check tuning_node & variant
node_name_2_node = {node["name"]: node for node in flow_dag[NODES]}
if tuning_node and tuning_node not in node_name_2_node:
raise InvalidFlowError(f"Node {tuning_node} not found in flow")
if tuning_node and variant:
try:
flow_dag[NODE_VARIANTS][tuning_node][VARIANTS][variant]
except KeyError as e:
raise InvalidFlowError(f"Variant {variant} not found for node {tuning_node}") from e
try:
node_variants = flow_dag.pop(NODE_VARIANTS, {}) if drop_node_variants else flow_dag.get(NODE_VARIANTS, {})
updated_nodes = []
for node in flow_dag.get(NODES, []):
if not node.get(USE_VARIANTS, False):
updated_nodes.append(node)
continue
# update variant
node_name = node["name"]
if node_name not in node_variants:
raise InvalidFlowError(f"No variant for the node {node_name}.")
variants_cfg = node_variants[node_name]
variant_id = variant if node_name == tuning_node else None
if not variant_id:
if DEFAULT_VAR_ID not in variants_cfg:
raise InvalidFlowError(f"Default variant id is not specified for {node_name}.")
variant_id = variants_cfg[DEFAULT_VAR_ID]
if variant_id not in variants_cfg.get(VARIANTS, {}):
raise InvalidFlowError(f"Cannot find the variant {variant_id} for {node_name}.")
variant_cfg = variants_cfg[VARIANTS][variant_id][NODE]
updated_nodes.append({"name": node_name, **variant_cfg})
flow_dag[NODES] = updated_nodes
except KeyError as e:
raise InvalidFlowError("Failed to overwrite tuning node with variant") from e
def overwrite_connections(flow_dag: dict, connections: dict, working_dir: PathLike):
if not connections:
return
if not isinstance(connections, dict):
raise InvalidFlowError(f"Invalid connections overwrite format: {connections}, only list is supported.")
# Load executable flow to check if connection is LLM connection
executable_flow = ExecutableFlow._from_dict(flow_dag=flow_dag, working_dir=Path(working_dir))
node_name_2_node = {node["name"]: node for node in flow_dag[NODES]}
for node_name, connection_dict in connections.items():
if node_name not in node_name_2_node:
raise InvalidFlowError(f"Node {node_name} not found in flow")
if not isinstance(connection_dict, dict):
raise InvalidFlowError(f"Invalid connection overwrite format: {connection_dict}, only dict is supported.")
node = node_name_2_node[node_name]
executable_node = executable_flow.get_node(node_name=node_name)
if executable_flow.is_llm_node(executable_node):
unsupported_keys = connection_dict.keys() - SUPPORTED_CONNECTION_FIELDS
if unsupported_keys:
raise InvalidFlowError(
f"Unsupported llm connection overwrite keys: {unsupported_keys},"
f" only {SUPPORTED_CONNECTION_FIELDS} are supported."
)
try:
connection = connection_dict.get(ConnectionFields.CONNECTION)
if connection:
node[ConnectionFields.CONNECTION] = connection
deploy_name = connection_dict.get(ConnectionFields.DEPLOYMENT_NAME)
if deploy_name:
node[INPUTS][ConnectionFields.DEPLOYMENT_NAME] = deploy_name
except KeyError as e:
raise InvalidFlowError(
f"Failed to overwrite llm node {node_name} with connections {connections}"
) from e
else:
connection_inputs = executable_flow.get_connection_input_names_for_node(node_name=node_name)
for c, v in connection_dict.items():
if c not in connection_inputs:
raise InvalidFlowError(f"Connection with name {c} not found in node {node_name}'s inputs")
node[INPUTS][c] = v
def overwrite_flow(flow_dag: dict, params_overrides: dict):
if not params_overrides:
return
# update flow dag & change nodes list to name: obj dict
flow_dag[NODES] = {node["name"]: node for node in flow_dag[NODES]}
# apply overrides on flow dag
for param, val in params_overrides.items():
objects.set_(flow_dag, param, val)
# revert nodes to list
flow_dag[NODES] = list(flow_dag[NODES].values())
The provided code snippet includes necessary dependencies for implementing the `variant_overwrite_context` function. Write a Python function `def variant_overwrite_context( flow: Flow, tuning_node: str = None, variant: str = None, connections: dict = None, *, overrides: dict = None, drop_node_variants: bool = False, )` to solve the following problem:
Override variant and connections in the flow.
Here is the function:
def variant_overwrite_context(
flow: Flow,
tuning_node: str = None,
variant: str = None,
connections: dict = None,
*,
overrides: dict = None,
drop_node_variants: bool = False,
):
"""Override variant and connections in the flow."""
flow_dag = flow._data
flow_dir_path = Path(flow.code)
if flow.additional_includes:
# Merge the flow folder and additional includes to temp folder for both eager flow & dag flow.
with _merge_local_code_and_additional_includes(code_path=flow_dir_path) as temp_dir:
if not isinstance(flow, EagerFlow):
# always overwrite variant since we need to overwrite default variant if not specified.
overwrite_variant(flow_dag, tuning_node, variant, drop_node_variants=drop_node_variants)
overwrite_connections(flow_dag, connections, working_dir=flow_dir_path)
overwrite_flow(flow_dag, overrides)
flow_dag.pop("additional_includes", None)
dump_flow_dag(flow_dag, Path(temp_dir))
flow = load_flow(temp_dir)
yield flow
elif isinstance(flow, EagerFlow):
# eager flow don't support overwrite variant
yield flow
else:
# Generate a flow, the code path points to the original flow folder,
# the dag path points to the temp dag file after overwriting variant.
with tempfile.TemporaryDirectory() as temp_dir:
overwrite_variant(flow_dag, tuning_node, variant, drop_node_variants=drop_node_variants)
overwrite_connections(flow_dag, connections, working_dir=flow_dir_path)
overwrite_flow(flow_dag, overrides)
flow_path = dump_flow_dag(flow_dag, Path(temp_dir))
flow = ProtectedFlow(code=flow_dir_path, path=flow_path, dag=flow_dag)
yield flow | Override variant and connections in the flow. |
4,156 | import contextlib
import hashlib
import json
import os
import platform
import re
import subprocess
import tempfile
import time
from collections import defaultdict
from os import PathLike
from pathlib import Path
from time import sleep
from types import GeneratorType
from typing import Any, Dict, List
import psutil
import pydash
from dotenv import load_dotenv
from pydash import objects
from promptflow._constants import STREAMING_ANIMATION_TIME
from promptflow._sdk._constants import (
ALL_CONNECTION_TYPES,
DEFAULT_VAR_ID,
INPUTS,
NODE,
NODE_VARIANTS,
NODES,
SUPPORTED_CONNECTION_FIELDS,
USE_VARIANTS,
VARIANTS,
ConnectionFields,
)
from promptflow._sdk._errors import InvalidFlowError, RunOperationError
from promptflow._sdk._load_functions import load_flow
from promptflow._sdk._utils import (
_merge_local_code_and_additional_includes,
get_local_connections_from_executable,
get_used_connection_names_from_dict,
update_dict_value_with_connections,
)
from promptflow._sdk.entities._eager_flow import EagerFlow
from promptflow._sdk.entities._flow import Flow, ProtectedFlow
from promptflow._utils.context_utils import _change_working_dir
from promptflow._utils.flow_utils import dump_flow_dag, load_flow_dag
from promptflow._utils.logger_utils import FileHandler, get_cli_sdk_logger
from promptflow.contracts.flow import Flow as ExecutableFlow
def resolve_generator_output_with_cache(
output: GeneratorType, generator_record: Dict[str, Any], *, generator_key: str
) -> List[str]:
"""Get the output of a generator. If the generator has been recorded, return the recorded result. Otherwise, record
the result and return it.
We use a separate generator_key instead of the output itself as the key in the generator_record in case the output
is not a valid dict key in some cases.
:param output: The generator to get the output from.
:type output: GeneratorType
:param generator_record: The record of the generator.
:type generator_record: dict
:param generator_key: The key of the generator in the record, need to be unique.
:type generator_key: str
:return: The output of the generator.
:rtype: str
"""
if isinstance(output, GeneratorType):
if generator_key in generator_record:
if hasattr(generator_record[generator_key], "items"):
output = iter(generator_record[generator_key].items)
else:
output = iter(generator_record[generator_key])
else:
if hasattr(output.gi_frame.f_locals, "proxy"):
proxy = output.gi_frame.f_locals["proxy"]
generator_record[generator_key] = proxy
else:
generator_record[generator_key] = list(output)
output = generator_record[generator_key]
return output
The provided code snippet includes necessary dependencies for implementing the `show_node_log_and_output` function. Write a Python function `def show_node_log_and_output(node_run_infos, show_node_output, generator_record)` to solve the following problem:
Show stdout and output of nodes.
Here is the function:
def show_node_log_and_output(node_run_infos, show_node_output, generator_record):
"""Show stdout and output of nodes."""
from colorama import Fore
for node_name, node_result in node_run_infos.items():
# Prefix of node stdout is "%Y-%m-%dT%H:%M:%S%z"
pattern = r"\[\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\+\d{4}\] "
if node_result.logs:
node_logs = re.sub(pattern, "", node_result.logs["stdout"])
if node_logs:
for log in node_logs.rstrip("\n").split("\n"):
print(f"{Fore.LIGHTBLUE_EX}[{node_name}]:", end=" ")
print(log)
if show_node_output:
print(f"{Fore.CYAN}{node_name}: ", end="")
# TODO executor return a type string of generator
node_output = node_result.output
if isinstance(node_result.output, GeneratorType):
node_output = "".join(
resolve_generator_output_with_cache(
node_output, generator_record, generator_key=f"nodes.{node_name}.output"
)
)
print(f"{Fore.LIGHTWHITE_EX}{node_output}") | Show stdout and output of nodes. |
4,157 | import contextlib
import hashlib
import json
import os
import platform
import re
import subprocess
import tempfile
import time
from collections import defaultdict
from os import PathLike
from pathlib import Path
from time import sleep
from types import GeneratorType
from typing import Any, Dict, List
import psutil
import pydash
from dotenv import load_dotenv
from pydash import objects
from promptflow._constants import STREAMING_ANIMATION_TIME
from promptflow._sdk._constants import (
ALL_CONNECTION_TYPES,
DEFAULT_VAR_ID,
INPUTS,
NODE,
NODE_VARIANTS,
NODES,
SUPPORTED_CONNECTION_FIELDS,
USE_VARIANTS,
VARIANTS,
ConnectionFields,
)
from promptflow._sdk._errors import InvalidFlowError, RunOperationError
from promptflow._sdk._load_functions import load_flow
from promptflow._sdk._utils import (
_merge_local_code_and_additional_includes,
get_local_connections_from_executable,
get_used_connection_names_from_dict,
update_dict_value_with_connections,
)
from promptflow._sdk.entities._eager_flow import EagerFlow
from promptflow._sdk.entities._flow import Flow, ProtectedFlow
from promptflow._utils.context_utils import _change_working_dir
from promptflow._utils.flow_utils import dump_flow_dag, load_flow_dag
from promptflow._utils.logger_utils import FileHandler, get_cli_sdk_logger
from promptflow.contracts.flow import Flow as ExecutableFlow
def resolve_generator_output_with_cache(
output: GeneratorType, generator_record: Dict[str, Any], *, generator_key: str
) -> List[str]:
def print_chat_output(output, generator_record, *, generator_key: str):
if isinstance(output, GeneratorType):
for event in resolve_generator_output_with_cache(output, generator_record, generator_key=generator_key):
print(event, end="")
# For better animation effects
time.sleep(STREAMING_ANIMATION_TIME)
# Print a new line at the end of the response
print()
else:
print(output) | null |
4,158 | import contextlib
import hashlib
import json
import os
import platform
import re
import subprocess
import tempfile
import time
from collections import defaultdict
from os import PathLike
from pathlib import Path
from time import sleep
from types import GeneratorType
from typing import Any, Dict, List
import psutil
import pydash
from dotenv import load_dotenv
from pydash import objects
from promptflow._constants import STREAMING_ANIMATION_TIME
from promptflow._sdk._constants import (
ALL_CONNECTION_TYPES,
DEFAULT_VAR_ID,
INPUTS,
NODE,
NODE_VARIANTS,
NODES,
SUPPORTED_CONNECTION_FIELDS,
USE_VARIANTS,
VARIANTS,
ConnectionFields,
)
from promptflow._sdk._errors import InvalidFlowError, RunOperationError
from promptflow._sdk._load_functions import load_flow
from promptflow._sdk._utils import (
_merge_local_code_and_additional_includes,
get_local_connections_from_executable,
get_used_connection_names_from_dict,
update_dict_value_with_connections,
)
from promptflow._sdk.entities._eager_flow import EagerFlow
from promptflow._sdk.entities._flow import Flow, ProtectedFlow
from promptflow._utils.context_utils import _change_working_dir
from promptflow._utils.flow_utils import dump_flow_dag, load_flow_dag
from promptflow._utils.logger_utils import FileHandler, get_cli_sdk_logger
from promptflow.contracts.flow import Flow as ExecutableFlow
def resolve_generator_output_with_cache(
output: GeneratorType, generator_record: Dict[str, Any], *, generator_key: str
) -> List[str]:
"""Get the output of a generator. If the generator has been recorded, return the recorded result. Otherwise, record
the result and return it.
We use a separate generator_key instead of the output itself as the key in the generator_record in case the output
is not a valid dict key in some cases.
:param output: The generator to get the output from.
:type output: GeneratorType
:param generator_record: The record of the generator.
:type generator_record: dict
:param generator_key: The key of the generator in the record, need to be unique.
:type generator_key: str
:return: The output of the generator.
:rtype: str
"""
if isinstance(output, GeneratorType):
if generator_key in generator_record:
if hasattr(generator_record[generator_key], "items"):
output = iter(generator_record[generator_key].items)
else:
output = iter(generator_record[generator_key])
else:
if hasattr(output.gi_frame.f_locals, "proxy"):
proxy = output.gi_frame.f_locals["proxy"]
generator_record[generator_key] = proxy
else:
generator_record[generator_key] = list(output)
output = generator_record[generator_key]
return output
def resolve_generator(flow_result, generator_record):
# resolve generator in flow result
for k, v in flow_result.run_info.output.items():
if isinstance(v, GeneratorType):
flow_output = "".join(
resolve_generator_output_with_cache(v, generator_record, generator_key=f"run.outputs.{k}")
)
flow_result.run_info.output[k] = flow_output
flow_result.run_info.result[k] = flow_output
flow_result.output[k] = flow_output
# resolve generator in node outputs
for node_name, node in flow_result.node_run_infos.items():
if isinstance(node.output, GeneratorType):
node_output = "".join(
resolve_generator_output_with_cache(
node.output, generator_record, generator_key=f"nodes.{node_name}.output"
)
)
node.output = node_output
node.result = node_output
return flow_result | null |
4,159 | import contextlib
import hashlib
import json
import os
import platform
import re
import subprocess
import tempfile
import time
from collections import defaultdict
from os import PathLike
from pathlib import Path
from time import sleep
from types import GeneratorType
from typing import Any, Dict, List
import psutil
import pydash
from dotenv import load_dotenv
from pydash import objects
from promptflow._constants import STREAMING_ANIMATION_TIME
from promptflow._sdk._constants import (
ALL_CONNECTION_TYPES,
DEFAULT_VAR_ID,
INPUTS,
NODE,
NODE_VARIANTS,
NODES,
SUPPORTED_CONNECTION_FIELDS,
USE_VARIANTS,
VARIANTS,
ConnectionFields,
)
from promptflow._sdk._errors import InvalidFlowError, RunOperationError
from promptflow._sdk._load_functions import load_flow
from promptflow._sdk._utils import (
_merge_local_code_and_additional_includes,
get_local_connections_from_executable,
get_used_connection_names_from_dict,
update_dict_value_with_connections,
)
from promptflow._sdk.entities._eager_flow import EagerFlow
from promptflow._sdk.entities._flow import Flow, ProtectedFlow
from promptflow._utils.context_utils import _change_working_dir
from promptflow._utils.flow_utils import dump_flow_dag, load_flow_dag
from promptflow._utils.logger_utils import FileHandler, get_cli_sdk_logger
from promptflow.contracts.flow import Flow as ExecutableFlow
def _start_process_in_background(args, executable_path=None):
if platform.system() == "Windows":
os.spawnve(os.P_DETACH, executable_path, args, os.environ)
else:
subprocess.Popen(" ".join(["nohup"] + args + ["&"]), shell=True, env=os.environ) | null |
4,160 | import contextlib
import hashlib
import json
import os
import platform
import re
import subprocess
import tempfile
import time
from collections import defaultdict
from os import PathLike
from pathlib import Path
from time import sleep
from types import GeneratorType
from typing import Any, Dict, List
import psutil
import pydash
from dotenv import load_dotenv
from pydash import objects
from promptflow._constants import STREAMING_ANIMATION_TIME
from promptflow._sdk._constants import (
ALL_CONNECTION_TYPES,
DEFAULT_VAR_ID,
INPUTS,
NODE,
NODE_VARIANTS,
NODES,
SUPPORTED_CONNECTION_FIELDS,
USE_VARIANTS,
VARIANTS,
ConnectionFields,
)
from promptflow._sdk._errors import InvalidFlowError, RunOperationError
from promptflow._sdk._load_functions import load_flow
from promptflow._sdk._utils import (
_merge_local_code_and_additional_includes,
get_local_connections_from_executable,
get_used_connection_names_from_dict,
update_dict_value_with_connections,
)
from promptflow._sdk.entities._eager_flow import EagerFlow
from promptflow._sdk.entities._flow import Flow, ProtectedFlow
from promptflow._utils.context_utils import _change_working_dir
from promptflow._utils.flow_utils import dump_flow_dag, load_flow_dag
from promptflow._utils.logger_utils import FileHandler, get_cli_sdk_logger
from promptflow.contracts.flow import Flow as ExecutableFlow
def _windows_stop_handler(experiment_name, post_process):
import win32pipe
# Create a named pipe to receive the cancel signal.
pipe_name = r"\\.\pipe\{}".format(experiment_name)
pipe = win32pipe.CreateNamedPipe(
pipe_name,
win32pipe.PIPE_ACCESS_DUPLEX,
win32pipe.PIPE_TYPE_MESSAGE | win32pipe.PIPE_WAIT,
1,
65536,
65536,
0,
None,
)
# Wait for connection to stop orchestrator
win32pipe.ConnectNamedPipe(pipe, None)
post_process() | null |
4,161 | import contextlib
import hashlib
import json
import os
import platform
import re
import subprocess
import tempfile
import time
from collections import defaultdict
from os import PathLike
from pathlib import Path
from time import sleep
from types import GeneratorType
from typing import Any, Dict, List
import psutil
import pydash
from dotenv import load_dotenv
from pydash import objects
from promptflow._constants import STREAMING_ANIMATION_TIME
from promptflow._sdk._constants import (
ALL_CONNECTION_TYPES,
DEFAULT_VAR_ID,
INPUTS,
NODE,
NODE_VARIANTS,
NODES,
SUPPORTED_CONNECTION_FIELDS,
USE_VARIANTS,
VARIANTS,
ConnectionFields,
)
from promptflow._sdk._errors import InvalidFlowError, RunOperationError
from promptflow._sdk._load_functions import load_flow
from promptflow._sdk._utils import (
_merge_local_code_and_additional_includes,
get_local_connections_from_executable,
get_used_connection_names_from_dict,
update_dict_value_with_connections,
)
from promptflow._sdk.entities._eager_flow import EagerFlow
from promptflow._sdk.entities._flow import Flow, ProtectedFlow
from promptflow._utils.context_utils import _change_working_dir
from promptflow._utils.flow_utils import dump_flow_dag, load_flow_dag
from promptflow._utils.logger_utils import FileHandler, get_cli_sdk_logger
from promptflow.contracts.flow import Flow as ExecutableFlow
def _calculate_snapshot(column_mapping, input_data, flow_path):
def calculate_files_content_hash(file_path):
file_content = {}
if not isinstance(file_path, (str, PathLike)) or not Path(file_path).exists():
return file_path
if Path(file_path).is_file():
with open(file_path, "r") as f:
absolute_path = Path(file_path).absolute().as_posix()
file_content[absolute_path] = hashlib.md5(f.read().encode("utf8")).hexdigest()
else:
for root, dirs, files in os.walk(file_path):
for ignore_item in ["__pycache__"]:
if ignore_item in dirs:
dirs.remove(ignore_item)
for file in files:
with open(os.path.join(root, file), "r") as f:
relative_path = (Path(root) / file).relative_to(Path(file_path)).as_posix()
try:
file_content[relative_path] = hashlib.md5(f.read().encode("utf8")).hexdigest()
except Exception as e:
raise e
return hashlib.md5(json.dumps(file_content, sort_keys=True).encode("utf-8")).hexdigest()
snapshot_content = {
"column_mapping": column_mapping,
"inputs": {key: calculate_files_content_hash(value) for key, value in input_data.items()},
"code": calculate_files_content_hash(flow_path),
}
return hashlib.md5(json.dumps(snapshot_content, sort_keys=True).encode("utf-8")).hexdigest() | null |
4,162 | import contextlib
import hashlib
import json
import os
import platform
import re
import subprocess
import tempfile
import time
from collections import defaultdict
from os import PathLike
from pathlib import Path
from time import sleep
from types import GeneratorType
from typing import Any, Dict, List
import psutil
import pydash
from dotenv import load_dotenv
from pydash import objects
from promptflow._constants import STREAMING_ANIMATION_TIME
from promptflow._sdk._constants import (
ALL_CONNECTION_TYPES,
DEFAULT_VAR_ID,
INPUTS,
NODE,
NODE_VARIANTS,
NODES,
SUPPORTED_CONNECTION_FIELDS,
USE_VARIANTS,
VARIANTS,
ConnectionFields,
)
from promptflow._sdk._errors import InvalidFlowError, RunOperationError
from promptflow._sdk._load_functions import load_flow
from promptflow._sdk._utils import (
_merge_local_code_and_additional_includes,
get_local_connections_from_executable,
get_used_connection_names_from_dict,
update_dict_value_with_connections,
)
from promptflow._sdk.entities._eager_flow import EagerFlow
from promptflow._sdk.entities._flow import Flow, ProtectedFlow
from promptflow._utils.context_utils import _change_working_dir
from promptflow._utils.flow_utils import dump_flow_dag, load_flow_dag
from promptflow._utils.logger_utils import FileHandler, get_cli_sdk_logger
from promptflow.contracts.flow import Flow as ExecutableFlow
logger = get_cli_sdk_logger()
def _stop_orchestrator_process(orchestrator):
try:
if platform.system() == "Windows":
import win32file
# Connect to named pipe to stop the orchestrator process.
win32file.CreateFile(
r"\\.\pipe\{}".format(orchestrator.experiment_name),
win32file.GENERIC_READ | win32file.GENERIC_WRITE,
0,
None,
win32file.OPEN_EXISTING,
0,
None,
)
else:
# Send terminate signal to orchestrator process.
process = psutil.Process(orchestrator.pid)
process.terminate()
except psutil.NoSuchProcess:
logger.debug("Experiment orchestrator process terminates abnormally.")
return
except Exception as e:
raise RunOperationError(
message=f"Experiment stopped failed with {e}",
)
# Wait for status updated
try:
while True:
psutil.Process(orchestrator.pid)
sleep(1)
except psutil.NoSuchProcess:
logger.debug("Experiment status has been updated.") | null |
4,163 | import contextlib
import hashlib
import json
import os
import platform
import re
import subprocess
import tempfile
import time
from collections import defaultdict
from os import PathLike
from pathlib import Path
from time import sleep
from types import GeneratorType
from typing import Any, Dict, List
import psutil
import pydash
from dotenv import load_dotenv
from pydash import objects
from promptflow._constants import STREAMING_ANIMATION_TIME
from promptflow._sdk._constants import (
ALL_CONNECTION_TYPES,
DEFAULT_VAR_ID,
INPUTS,
NODE,
NODE_VARIANTS,
NODES,
SUPPORTED_CONNECTION_FIELDS,
USE_VARIANTS,
VARIANTS,
ConnectionFields,
)
from promptflow._sdk._errors import InvalidFlowError, RunOperationError
from promptflow._sdk._load_functions import load_flow
from promptflow._sdk._utils import (
_merge_local_code_and_additional_includes,
get_local_connections_from_executable,
get_used_connection_names_from_dict,
update_dict_value_with_connections,
)
from promptflow._sdk.entities._eager_flow import EagerFlow
from promptflow._sdk.entities._flow import Flow, ProtectedFlow
from promptflow._utils.context_utils import _change_working_dir
from promptflow._utils.flow_utils import dump_flow_dag, load_flow_dag
from promptflow._utils.logger_utils import FileHandler, get_cli_sdk_logger
from promptflow.contracts.flow import Flow as ExecutableFlow
logger = get_cli_sdk_logger()
The provided code snippet includes necessary dependencies for implementing the `_set_up_experiment_log_handler` function. Write a Python function `def _set_up_experiment_log_handler(experiment_path, index=None)` to solve the following problem:
Set up file handler to record experiment execution. If not set index, it will record logs in a new file. :param experiment_path: Experiment path. :type experiment_path: str :param index: The number of attempt to execution experiment. :type index: int :return: File handler, the number of attempt to execution experiment. :rtype: ~promptflow.utils.logger_utils.FileHandler, int
Here is the function:
def _set_up_experiment_log_handler(experiment_path, index=None):
"""
Set up file handler to record experiment execution. If not set index, it will record logs in a new file.
:param experiment_path: Experiment path.
:type experiment_path: str
:param index: The number of attempt to execution experiment.
:type index: int
:return: File handler, the number of attempt to execution experiment.
:rtype: ~promptflow.utils.logger_utils.FileHandler, int
"""
log_folder = Path(experiment_path) / "logs"
log_folder.mkdir(exist_ok=True, parents=True)
if index is None:
# Get max index in logs folder
index = 0
for filename in os.listdir(log_folder):
result = re.match(r"exp\.attempt\_(\d+)\.log", filename)
if result:
try:
index = max(index, int(result.groups()[0]) + 1)
except Exception as e:
logger.debug(f"Get index of log file failed: {e}")
log_path = Path(experiment_path) / "logs" / f"exp.attempt_{index}.log"
logger.info(f"Experiment execution log records in {log_path}")
file_handler = FileHandler(file_path=log_path)
return file_handler, index | Set up file handler to record experiment execution. If not set index, it will record logs in a new file. :param experiment_path: Experiment path. :type experiment_path: str :param index: The number of attempt to execution experiment. :type index: int :return: File handler, the number of attempt to execution experiment. :rtype: ~promptflow.utils.logger_utils.FileHandler, int |
4,164 | import argparse
import copy
import json
import os
import platform
import signal
import subprocess
import sys
import tempfile
import uuid
from concurrent import futures
from concurrent.futures import ThreadPoolExecutor
from dataclasses import is_dataclass
from datetime import datetime
from pathlib import Path
from typing import Union
import psutil
from promptflow._sdk._constants import (
PF_TRACE_CONTEXT,
PF_TRACE_CONTEXT_ATTR,
PROMPT_FLOW_DIR_NAME,
ContextAttributeKey,
ExperimentNodeRunStatus,
ExperimentNodeType,
ExperimentStatus,
FlowRunProperties,
RunTypes,
)
from promptflow._sdk._errors import (
ExperimentCommandRunError,
ExperimentHasCycle,
ExperimentNodeRunFailedError,
ExperimentNotFoundError,
ExperimentValueError,
)
from promptflow._sdk._orm.experiment import Experiment as ORMExperiment
from promptflow._sdk._orm.experiment_node_run import ExperimentNodeRun as ORMExperimentNodeRun
from promptflow._sdk._orm.orchestrator import Orchestrator as ORMOrchestrator
from promptflow._sdk._orm.run_info import RunInfo as ORMRunInfo
from promptflow._sdk._submitter import RunSubmitter
from promptflow._sdk._submitter.utils import (
SubmitterHelper,
_calculate_snapshot,
_set_up_experiment_log_handler,
_start_process_in_background,
_stop_orchestrator_process,
_windows_stop_handler,
)
from promptflow._sdk._utils import overwrite_null_std_logger
from promptflow._sdk.entities import Run
from promptflow._sdk.entities._experiment import Experiment, ExperimentTemplate
from promptflow._sdk.entities._flow import ProtectedFlow
from promptflow._sdk.operations import RunOperations
from promptflow._sdk.operations._local_storage_operations import LocalStorageOperations
from promptflow._utils.inputs_mapping_utils import apply_inputs_mapping
from promptflow._utils.load_data import load_data
from promptflow._utils.logger_utils import get_cli_sdk_logger
from promptflow.contracts.run_info import Status
from promptflow.contracts.run_mode import RunMode
from promptflow.exceptions import ErrorTarget, UserErrorException
The provided code snippet includes necessary dependencies for implementing the `add_start_orchestrator_action` function. Write a Python function `def add_start_orchestrator_action(subparsers)` to solve the following problem:
Add action to start orchestrator.
Here is the function:
def add_start_orchestrator_action(subparsers):
"""Add action to start orchestrator."""
start_orchestrator_parser = subparsers.add_parser(
"start",
description="Start orchestrator.",
)
start_orchestrator_parser.add_argument("--experiment", type=str, help="Experiment name")
start_orchestrator_parser.add_argument("--nodes", type=str, help="Nodes to be executed", nargs="+")
start_orchestrator_parser.add_argument("--from-nodes", type=str, help="Nodes branch to be executed", nargs="+")
start_orchestrator_parser.add_argument("--attempt", type=str, help="The number of attempt to execute experiment.")
start_orchestrator_parser.add_argument("--session", type=str, help="Session id of experiment execution.")
start_orchestrator_parser.set_defaults(action="start") | Add action to start orchestrator. |
4,165 | import json
import os
import typing
import urllib.parse
from opentelemetry import trace
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.environment_variables import OTEL_EXPORTER_OTLP_ENDPOINT
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from promptflow._constants import (
OTEL_RESOURCE_SERVICE_NAME,
SpanAttributeFieldName,
SpanResourceAttributesFieldName,
TraceEnvironmentVariableName,
)
from promptflow._core.operation_context import OperationContext
from promptflow._sdk._configuration import Configuration
from promptflow._sdk._constants import (
PF_TRACE_CONTEXT,
PF_TRACE_CONTEXT_ATTR,
AzureMLWorkspaceTriad,
ContextAttributeKey,
)
from promptflow._sdk._service.entry import entry
from promptflow._sdk._service.utils.utils import get_port_from_config, is_pfs_service_healthy, is_port_in_use
from promptflow._sdk._utils import extract_workspace_triad_from_trace_provider
from promptflow._utils.logger_utils import get_cli_sdk_logger
from promptflow.tracing._openai_injector import inject_openai_api
from promptflow.tracing._start_trace import _force_set_tracer_provider, _is_tracer_provider_set
logger = get_cli_sdk_logger()
def _inject_attrs_to_op_ctx(attrs: typing.Dict[str, str]) -> None:
if len(attrs) == 0:
return
logger.debug("Inject attributes %s to context", attrs)
op_ctx = OperationContext.get_instance()
for attr_key, attr_value in attrs.items():
op_ctx._add_otel_attributes(attr_key, attr_value)
def _invoke_pf_svc() -> str:
port = get_port_from_config(create_if_not_exists=True)
port = str(port)
cmd_args = ["start", "--port", port]
if is_port_in_use(int(port)):
if not is_pfs_service_healthy(port):
cmd_args.append("--force")
else:
return port
entry(cmd_args)
logger.debug("Prompt flow service is serving on port %s", port)
return port
def _get_ws_triad_from_pf_config() -> typing.Optional[AzureMLWorkspaceTriad]:
ws_arm_id = Configuration.get_instance().get_trace_provider()
return extract_workspace_triad_from_trace_provider(ws_arm_id) if ws_arm_id is not None else None
def _print_tracing_url_from_local(
pfs_port: str,
session_id: typing.Optional[str],
exp: typing.Optional[str] = None,
run: typing.Optional[str] = None,
) -> None:
url = f"http://localhost:{pfs_port}/v1.0/ui/traces"
if run is not None:
url += f"?run={run}"
elif exp is not None:
url += f"?experiment={exp}"
elif session_id is not None:
url += f"?session={session_id}"
print(f"You can view the traces from local: {url}")
def _print_tracing_url_from_azure_portal(
ws_triad: typing.Optional[AzureMLWorkspaceTriad],
session_id: typing.Optional[str],
exp: typing.Optional[str] = None,
run: typing.Optional[str] = None,
) -> None:
if ws_triad is None:
return
url = get_ws_tracing_base_url(ws_triad)
query = None
if run is not None:
query = '{"batchRunId":"' + run + '"}'
elif exp is not None:
# not consider experiment for now
pass
elif session_id is not None:
query = '{"sessionId":"' + session_id + '"}'
# urllib.parse.quote to encode the query parameter
if query is not None:
url += f"&searchText={urllib.parse.quote(query)}"
print(f"You can view the traces in cloud from Azure portal: {url}")
def _inject_res_attrs_to_environ(
pfs_port: str,
session_id: typing.Optional[str],
exp: typing.Optional[str] = None,
ws_triad: typing.Optional[AzureMLWorkspaceTriad] = None,
) -> None:
if session_id is not None:
os.environ[TraceEnvironmentVariableName.SESSION_ID] = session_id
if exp is not None:
os.environ[TraceEnvironmentVariableName.EXPERIMENT] = exp
if ws_triad is not None:
os.environ[TraceEnvironmentVariableName.SUBSCRIPTION_ID] = ws_triad.subscription_id
os.environ[TraceEnvironmentVariableName.RESOURCE_GROUP_NAME] = ws_triad.resource_group_name
os.environ[TraceEnvironmentVariableName.WORKSPACE_NAME] = ws_triad.workspace_name
# we will not overwrite the value if it is already set
if OTEL_EXPORTER_OTLP_ENDPOINT not in os.environ:
os.environ[OTEL_EXPORTER_OTLP_ENDPOINT] = f"http://localhost:{pfs_port}/v1/traces"
def setup_exporter_to_pfs() -> None:
# get resource attributes from environment
session_id = os.getenv(TraceEnvironmentVariableName.SESSION_ID, None)
exp = os.getenv(TraceEnvironmentVariableName.EXPERIMENT, None)
# local to cloud scenario: workspace triad in resource.attributes
workspace_triad = None
subscription_id = os.getenv(TraceEnvironmentVariableName.SUBSCRIPTION_ID, None)
resource_group_name = os.getenv(TraceEnvironmentVariableName.RESOURCE_GROUP_NAME, None)
workspace_name = os.getenv(TraceEnvironmentVariableName.WORKSPACE_NAME, None)
if all([subscription_id, resource_group_name, workspace_name]):
workspace_triad = AzureMLWorkspaceTriad(
subscription_id=subscription_id,
resource_group_name=resource_group_name,
workspace_name=workspace_name,
)
# create resource, or merge to existing resource
res = _create_or_merge_res(session_id=session_id, exp=exp, ws_triad=workspace_triad)
tracer_provider = TracerProvider(resource=res)
# get OTLP endpoint from environment
endpoint = os.getenv(OTEL_EXPORTER_OTLP_ENDPOINT)
if endpoint is not None:
# create OTLP span exporter if endpoint is set
otlp_span_exporter = OTLPSpanExporter(endpoint=endpoint)
tracer_provider.add_span_processor(BatchSpanProcessor(otlp_span_exporter))
# set tracer provider
if _is_tracer_provider_set():
_force_set_tracer_provider(tracer_provider)
else:
trace.set_tracer_provider(tracer_provider)
def start_trace_with_devkit(
session_id: typing.Optional[str],
attrs: typing.Optional[typing.Dict[str, str]] = None,
run: typing.Optional[str] = None,
) -> None:
# honor and set attributes if user has specified
if isinstance(attrs, dict):
_inject_attrs_to_op_ctx(attrs)
# experiment related attributes, pass from environment
env_tracing_ctx = os.environ.get(PF_TRACE_CONTEXT, None)
logger.debug("Read tracing context from environment: %s", env_tracing_ctx)
env_attrs = dict(json.loads(env_tracing_ctx)).get(PF_TRACE_CONTEXT_ATTR) if env_tracing_ctx else dict()
exp = env_attrs.get(ContextAttributeKey.EXPERIMENT, None)
ref_line_run_id = env_attrs.get(ContextAttributeKey.REFERENCED_LINE_RUN_ID, None)
op_ctx = OperationContext.get_instance()
# remove `referenced.line_run_id` from context to avoid stale value set by previous node
if ref_line_run_id is None:
op_ctx._remove_otel_attributes(SpanAttributeFieldName.REFERENCED_LINE_RUN_ID)
else:
op_ctx._add_otel_attributes(SpanAttributeFieldName.REFERENCED_LINE_RUN_ID, ref_line_run_id)
# local to cloud feature
ws_triad = _get_ws_triad_from_pf_config()
# invoke prompt flow service
pfs_port = _invoke_pf_svc()
_inject_res_attrs_to_environ(pfs_port=pfs_port, session_id=session_id, exp=exp, ws_triad=ws_triad)
# instrument openai and setup exporter to pfs here for flex mode
inject_openai_api()
setup_exporter_to_pfs()
# print tracing url(s)
_print_tracing_url_from_local(pfs_port=pfs_port, session_id=session_id, exp=exp, run=run)
_print_tracing_url_from_azure_portal(ws_triad=ws_triad, session_id=session_id, exp=exp, run=run) | null |
4,166 | import os
from pathlib import Path, PureWindowsPath
from typing import Any, Iterable, List, Optional, Tuple, Union
from ._pathspec import GitWildMatchPattern, normalize_file
def convert_windows_path_to_unix(path: Union[str, os.PathLike]) -> str:
return PureWindowsPath(path).as_posix() | null |
4,167 | import os
from pathlib import Path, PureWindowsPath
from typing import Any, Iterable, List, Optional, Tuple, Union
from ._pathspec import GitWildMatchPattern, normalize_file
class IgnoreFile(object):
def __init__(self, file_path: Optional[Union[str, Path]] = None):
"""Base class for handling .gitignore and .amlignore files.
:param file_path: Relative path, or absolute path to the ignore file.
"""
path = Path(file_path).resolve() if file_path else None
self._path = path
self._path_spec = None
def exists(self) -> bool:
"""Checks if ignore file exists."""
return self._file_exists()
def _file_exists(self) -> bool:
return self._path and self._path.exists()
def base_path(self) -> Path:
return self._path.parent
def _get_ignore_list(self) -> List[str]:
"""Get ignore list from ignore file contents."""
if not self.exists():
return []
if self._file_exists():
with open(self._path, "r") as fh:
return [line.rstrip() for line in fh if line]
return []
def _create_pathspec(self) -> List[GitWildMatchPattern]:
"""Creates path specification based on ignore list."""
return [GitWildMatchPattern(ignore) for ignore in self._get_ignore_list()]
def _get_rel_path(self, file_path: Union[str, Path]) -> Optional[str]:
"""Get relative path of given file_path."""
file_path = Path(file_path).absolute()
try:
# use os.path.relpath instead of Path.relative_to in case file_path is not a child of self.base_path
return os.path.relpath(file_path, self.base_path)
except ValueError:
# 2 paths are on different drives
return None
def is_file_excluded(self, file_path: Union[str, Path]) -> bool:
"""Checks if given file_path is excluded.
:param file_path: File path to be checked against ignore file specifications
"""
# TODO: current design of ignore file can't distinguish between files and directories of the same name
if self._path_spec is None:
self._path_spec = self._create_pathspec()
if not self._path_spec:
return False
file_path = self._get_rel_path(file_path)
if file_path is None:
return True
norm_file = normalize_file(file_path)
matched = False
for pattern in self._path_spec:
if pattern.include is not None:
if pattern.match_file(norm_file) is not None:
matched = pattern.include
return matched
def path(self) -> Union[Path, str]:
return self._path
class AmlIgnoreFile(IgnoreFile):
def __init__(self, directory_path: Union[Path, str]):
file_path = Path(directory_path).joinpath(AML_IGNORE_FILE_NAME)
super(AmlIgnoreFile, self).__init__(file_path)
class GitIgnoreFile(IgnoreFile):
def __init__(self, directory_path: Union[Path, str]):
file_path = Path(directory_path).joinpath(GIT_IGNORE_FILE_NAME)
super(GitIgnoreFile, self).__init__(file_path)
The provided code snippet includes necessary dependencies for implementing the `get_ignore_file` function. Write a Python function `def get_ignore_file(directory_path: Union[Path, str]) -> Optional[IgnoreFile]` to solve the following problem:
Finds and returns IgnoreFile object based on ignore file found in directory_path. .amlignore takes precedence over .gitignore and if no file is found, an empty IgnoreFile object will be returned. The ignore file must be in the root directory. :param directory_path: Path to the (root) directory where ignore file is located
Here is the function:
def get_ignore_file(directory_path: Union[Path, str]) -> Optional[IgnoreFile]:
"""Finds and returns IgnoreFile object based on ignore file found in directory_path.
.amlignore takes precedence over .gitignore and if no file is found, an empty
IgnoreFile object will be returned.
The ignore file must be in the root directory.
:param directory_path: Path to the (root) directory where ignore file is located
"""
aml_ignore = AmlIgnoreFile(directory_path)
git_ignore = GitIgnoreFile(directory_path)
if aml_ignore.exists():
return aml_ignore
if git_ignore.exists():
return git_ignore
return IgnoreFile() | Finds and returns IgnoreFile object based on ignore file found in directory_path. .amlignore takes precedence over .gitignore and if no file is found, an empty IgnoreFile object will be returned. The ignore file must be in the root directory. :param directory_path: Path to the (root) directory where ignore file is located |
4,168 | import os
from pathlib import Path, PureWindowsPath
from typing import Any, Iterable, List, Optional, Tuple, Union
from ._pathspec import GitWildMatchPattern, normalize_file
class IgnoreFile(object):
def __init__(self, file_path: Optional[Union[str, Path]] = None):
"""Base class for handling .gitignore and .amlignore files.
:param file_path: Relative path, or absolute path to the ignore file.
"""
path = Path(file_path).resolve() if file_path else None
self._path = path
self._path_spec = None
def exists(self) -> bool:
"""Checks if ignore file exists."""
return self._file_exists()
def _file_exists(self) -> bool:
return self._path and self._path.exists()
def base_path(self) -> Path:
return self._path.parent
def _get_ignore_list(self) -> List[str]:
"""Get ignore list from ignore file contents."""
if not self.exists():
return []
if self._file_exists():
with open(self._path, "r") as fh:
return [line.rstrip() for line in fh if line]
return []
def _create_pathspec(self) -> List[GitWildMatchPattern]:
"""Creates path specification based on ignore list."""
return [GitWildMatchPattern(ignore) for ignore in self._get_ignore_list()]
def _get_rel_path(self, file_path: Union[str, Path]) -> Optional[str]:
"""Get relative path of given file_path."""
file_path = Path(file_path).absolute()
try:
# use os.path.relpath instead of Path.relative_to in case file_path is not a child of self.base_path
return os.path.relpath(file_path, self.base_path)
except ValueError:
# 2 paths are on different drives
return None
def is_file_excluded(self, file_path: Union[str, Path]) -> bool:
"""Checks if given file_path is excluded.
:param file_path: File path to be checked against ignore file specifications
"""
# TODO: current design of ignore file can't distinguish between files and directories of the same name
if self._path_spec is None:
self._path_spec = self._create_pathspec()
if not self._path_spec:
return False
file_path = self._get_rel_path(file_path)
if file_path is None:
return True
norm_file = normalize_file(file_path)
matched = False
for pattern in self._path_spec:
if pattern.include is not None:
if pattern.match_file(norm_file) is not None:
matched = pattern.include
return matched
def path(self) -> Union[Path, str]:
return self._path
def traverse_directory(
root: str,
files: List[str],
*,
prefix: str,
ignore_file: IgnoreFile = IgnoreFile(),
# keep this for backward compatibility
**kwargs: Any,
) -> Iterable[Tuple[str, str]]:
"""Enumerate all files in the given directory and compose paths for them to be uploaded to in the remote storage.
e.g.
[/mnt/c/Users/dipeck/upload_files/my_file1.txt,
/mnt/c/Users/dipeck/upload_files/my_file2.txt] -->
[(/mnt/c/Users/dipeck/upload_files/my_file1.txt, LocalUpload/<guid>/upload_files/my_file1.txt),
(/mnt/c/Users/dipeck/upload_files/my_file2.txt, LocalUpload/<guid>/upload_files/my_file2.txt))]
:param root: Root directory path
:type root: str
:param files: List of all file paths in the directory
:type files: List[str]
:param prefix: Remote upload path for project directory (e.g. LocalUpload/<guid>/project_dir)
:type prefix: str
:param ignore_file: The .amlignore or .gitignore file in the project directory
:type ignore_file: azure.ai.ml._utils._asset_utils.IgnoreFile
:return: Zipped list of tuples representing the local path and remote destination path for each file
:rtype: Iterable[Tuple[str, str]]
"""
# Normalize Windows paths. Note that path should be resolved first as long part will be converted to a shortcut in
# Windows. For example, C:\Users\too-long-user-name\test will be converted to C:\Users\too-lo~1\test by default.
# Refer to https://en.wikipedia.org/wiki/8.3_filename for more details.
root = Path(root).resolve().absolute()
# filter out files excluded by the ignore file
# TODO: inner ignore file won't take effect. A merged IgnoreFile need to be generated in code resolution.
origin_file_paths = [
root.joinpath(filename)
for filename in files
if not ignore_file.is_file_excluded(root.joinpath(filename).as_posix())
]
result = []
for origin_file_path in origin_file_paths:
relative_path = origin_file_path.relative_to(root)
result.append((_resolve_path(origin_file_path).as_posix(), Path(prefix).joinpath(relative_path).as_posix()))
return result
The provided code snippet includes necessary dependencies for implementing the `get_upload_files_from_folder` function. Write a Python function `def get_upload_files_from_folder( path: Union[str, Path], *, prefix: str = "", ignore_file: IgnoreFile = IgnoreFile() ) -> List[Tuple[str, str]]` to solve the following problem:
Enumerate all files in the given directory and compose paths for them to be uploaded to in the remote storage. :param path: Path to the directory to be uploaded :type path: str :param prefix: Prefix for remote storage path :type prefix: str :param ignore_file: Ignore file object :type ignore_file: IgnoreFile :return: List of tuples of (local path, remote path) :rtype: list
Here is the function:
def get_upload_files_from_folder(
path: Union[str, Path], *, prefix: str = "", ignore_file: IgnoreFile = IgnoreFile()
) -> List[Tuple[str, str]]:
"""Enumerate all files in the given directory and compose paths for them to be uploaded to in the remote storage.
:param path: Path to the directory to be uploaded
:type path: str
:param prefix: Prefix for remote storage path
:type prefix: str
:param ignore_file: Ignore file object
:type ignore_file: IgnoreFile
:return: List of tuples of (local path, remote path)
:rtype: list
"""
path = Path(path)
upload_paths = []
for root, _, files in os.walk(path, followlinks=True):
upload_paths += list(
traverse_directory(
root,
files,
prefix=Path(prefix).joinpath(Path(root).relative_to(path)).as_posix(),
ignore_file=ignore_file,
)
)
return upload_paths | Enumerate all files in the given directory and compose paths for them to be uploaded to in the remote storage. :param path: Path to the directory to be uploaded :type path: str :param prefix: Prefix for remote storage path :type prefix: str :param ignore_file: Ignore file object :type ignore_file: IgnoreFile :return: List of tuples of (local path, remote path) :rtype: list |
4,169 | import dataclasses
import os
import posixpath
import re
import warnings
from typing import Any, AnyStr, Iterable, Iterator
from typing import Match as MatchHint
from typing import Optional
from typing import Pattern as PatternHint
from typing import Tuple, Union
NORMALIZE_PATH_SEPS = [sep for sep in [os.sep, os.altsep] if sep and sep != posixpath.sep]
The provided code snippet includes necessary dependencies for implementing the `normalize_file` function. Write a Python function `def normalize_file(file, separators=None)` to solve the following problem:
Normalizes the file path to use the POSIX path separator (i.e., ``'/'``), and make the paths relative (remove leading ``'/'``). *file* (:class:`str` or :class:`pathlib.PurePath`) is the file path. *separators* (:class:`~collections.abc.Collection` of :class:`str`; or :data:`None`) optionally contains the path separators to normalize. This does not need to include the POSIX path separator (``'/'``), but including it will not affect the results. Default is :data:`None` for :data:`NORMALIZE_PATH_SEPS`. To prevent normalization, pass an empty container (e.g., an empty tuple ``()``). Returns the normalized file path (:class:`str`).
Here is the function:
def normalize_file(file, separators=None):
# type - (Union[Text, PathLike], Optional[Collection[Text]]) -> Text
"""
Normalizes the file path to use the POSIX path separator (i.e.,
``'/'``), and make the paths relative (remove leading ``'/'``).
*file* (:class:`str` or :class:`pathlib.PurePath`) is the file path.
*separators* (:class:`~collections.abc.Collection` of :class:`str`; or
:data:`None`) optionally contains the path separators to normalize.
This does not need to include the POSIX path separator (``'/'``), but
including it will not affect the results. Default is :data:`None` for
:data:`NORMALIZE_PATH_SEPS`. To prevent normalization, pass an empty
container (e.g., an empty tuple ``()``).
Returns the normalized file path (:class:`str`).
"""
# Normalize path separators.
if separators is None:
separators = NORMALIZE_PATH_SEPS
# Convert path object to string.
norm_file = str(file)
for sep in separators:
norm_file = norm_file.replace(sep, posixpath.sep)
if norm_file.startswith("/"):
# Make path relative.
norm_file = norm_file[1:]
elif norm_file.startswith("./"):
# Remove current directory prefix.
norm_file = norm_file[2:]
return norm_file | Normalizes the file path to use the POSIX path separator (i.e., ``'/'``), and make the paths relative (remove leading ``'/'``). *file* (:class:`str` or :class:`pathlib.PurePath`) is the file path. *separators* (:class:`~collections.abc.Collection` of :class:`str`; or :data:`None`) optionally contains the path separators to normalize. This does not need to include the POSIX path separator (``'/'``), but including it will not affect the results. Default is :data:`None` for :data:`NORMALIZE_PATH_SEPS`. To prevent normalization, pass an empty container (e.g., an empty tuple ``()``). Returns the normalized file path (:class:`str`). |
4,170 | from os import PathLike
from pathlib import Path
from typing import IO, AnyStr, Optional, Union
from dotenv import dotenv_values
from .._utils.logger_utils import get_cli_sdk_logger
from .._utils.yaml_utils import load_yaml
from ._errors import MultipleExperimentTemplateError, NoExperimentTemplateError
from .entities import Run
from .entities._connection import CustomConnection, _Connection
from .entities._experiment import Experiment, ExperimentTemplate
from .entities._flow import Flow
class Flow(FlowBase):
"""This class is used to represent a flow."""
def __init__(
self,
code: Union[str, PathLike],
path: Union[str, PathLike],
dag: dict,
**kwargs,
):
self.variant = kwargs.pop("variant", None) or {}
super().__init__(data=dag, code=code, path=path, **kwargs)
def _is_eager_flow(cls, data: dict):
"""Check if the flow is an eager flow. Use field 'entry' to determine."""
# If entry specified, it's an eager flow.
return data.get("entry")
def load(
cls,
source: Union[str, PathLike],
entry: str = None,
raise_error=True,
**kwargs,
):
from promptflow._sdk.entities._eager_flow import EagerFlow
source_path = Path(source)
if not source_path.exists():
raise UserErrorException(f"Source {source_path.absolute().as_posix()} does not exist")
flow_path = resolve_flow_path(source_path)
if not flow_path.exists():
raise UserErrorException(f"Flow file {flow_path.absolute().as_posix()} does not exist")
if flow_path.suffix in [".yaml", ".yml"]:
# read flow file to get hash
with open(flow_path, "r", encoding=DEFAULT_ENCODING) as f:
flow_content = f.read()
data = load_yaml_string(flow_content)
content_hash = hash(flow_content)
is_eager_flow = cls._is_eager_flow(data)
is_async_call = kwargs.pop("is_async_call", False)
if is_eager_flow:
return EagerFlow._load(path=flow_path, data=data, raise_error=raise_error, **kwargs)
else:
# TODO: schema validation and warning on unknown fields
if is_async_call:
return AsyncProtectedFlow._load(path=flow_path, dag=data, content_hash=content_hash, **kwargs)
else:
return ProtectedFlow._load(path=flow_path, dag=data, content_hash=content_hash, **kwargs)
# if non-YAML file is provided, raise user error exception
raise UserErrorException("Source must be a directory or a 'flow.dag.yaml' file")
def _init_executable(self, tuning_node=None, variant=None):
from promptflow._sdk._submitter import variant_overwrite_context
from promptflow.contracts.flow import Flow as ExecutableFlow
if not tuning_node and not variant:
# for DAG flow, use data to init executable to improve performance
return ExecutableFlow._from_dict(flow_dag=self._data, working_dir=self.code)
# TODO: check if there is potential bug here
# this is a little wired:
# 1. the executable is created from a temp folder when there is additional includes
# 2. after the executable is returned, the temp folder is deleted
with variant_overwrite_context(self, tuning_node, variant) as flow:
return ExecutableFlow.from_yaml(flow_file=flow.path, working_dir=flow.code)
def __eq__(self, other):
if isinstance(other, Flow):
return self._content_hash == other._content_hash and self.context == other.context
return False
def __hash__(self):
return hash(self.context) ^ self._content_hash
The provided code snippet includes necessary dependencies for implementing the `load_flow` function. Write a Python function `def load_flow( source: Union[str, PathLike, IO[AnyStr]], is_async_call: Optional[bool] = None, **kwargs, ) -> Flow` to solve the following problem:
Load flow from YAML file. :param source: The local yaml source of a flow. Must be a path to a local file. If the source is a path, it will be open and read. An exception is raised if the file does not exist. :type source: Union[PathLike, str] :param is_async_call: Optional argument to indicate the return value is an async function. If True, the return value is an async function, otherwise, it is a sync function. :type is_async_call: bool :return: A Flow object :rtype: Flow
Here is the function:
def load_flow(
source: Union[str, PathLike, IO[AnyStr]],
is_async_call: Optional[bool] = None,
**kwargs,
) -> Flow:
"""Load flow from YAML file.
:param source: The local yaml source of a flow. Must be a path to a local file.
If the source is a path, it will be open and read.
An exception is raised if the file does not exist.
:type source: Union[PathLike, str]
:param is_async_call: Optional argument to indicate the return value is an async function.
If True, the return value is an async function, otherwise, it is a sync function.
:type is_async_call: bool
:return: A Flow object
:rtype: Flow
"""
return Flow.load(source, is_async_call=is_async_call, **kwargs) | Load flow from YAML file. :param source: The local yaml source of a flow. Must be a path to a local file. If the source is a path, it will be open and read. An exception is raised if the file does not exist. :type source: Union[PathLike, str] :param is_async_call: Optional argument to indicate the return value is an async function. If True, the return value is an async function, otherwise, it is a sync function. :type is_async_call: bool :return: A Flow object :rtype: Flow |
4,171 | from os import PathLike
from pathlib import Path
from typing import IO, AnyStr, Optional, Union
from dotenv import dotenv_values
from .._utils.logger_utils import get_cli_sdk_logger
from .._utils.yaml_utils import load_yaml
from ._errors import MultipleExperimentTemplateError, NoExperimentTemplateError
from .entities import Run
from .entities._connection import CustomConnection, _Connection
from .entities._experiment import Experiment, ExperimentTemplate
from .entities._flow import Flow
def load_yaml(source: Optional[Union[AnyStr, PathLike, IO]]) -> Dict:
# null check - just return an empty dict.
# Certain CLI commands rely on this behavior to produce a resource
# via CLI, which is then populated through CLArgs.
"""Load a local YAML file or a readable stream object.
.. note::
1. For a local file yaml
.. code-block:: python
yaml_path = "path/to/yaml"
content = load_yaml(yaml_path)
2. For a readable stream object
.. code-block:: python
with open("path/to/yaml", "r", encoding="utf-8") as f:
content = load_yaml(f)
:param source: The relative or absolute path to the local file, or a readable stream object.
:type source: str
:return: A dictionary representation of the local file's contents.
:rtype: Dict
"""
if source is None:
return {}
# pylint: disable=redefined-builtin
input = None
must_open_file = False
try: # check source type by duck-typing it as an IOBase
readable = source.readable()
if not readable: # source is misformatted stream or file
msg = "File Permissions Error: The already-open \n\n inputted file is not readable."
raise PermissionError(msg)
# source is an already-open stream or file, we can read() from it directly.
input = source
except AttributeError:
# source has no writable() function, assume it's a string or file path.
must_open_file = True
if must_open_file: # If supplied a file path, open it.
try:
input = open(source, "r", encoding=DEFAULT_ENCODING)
except OSError: # FileNotFoundError introduced in Python 3
msg = "No such file or directory: {}"
raise FileNotFoundError(msg.format(source))
# input should now be a readable file or stream. Parse it.
try:
yaml = YAML()
yaml.preserve_quotes = True
cfg = yaml.load(input)
except YAMLError as e:
msg = f"Error while parsing yaml file: {source} \n\n {str(e)}"
raise YAMLError(msg)
finally:
if must_open_file:
input.close()
return cfg
The provided code snippet includes necessary dependencies for implementing the `load_run` function. Write a Python function `def load_run( source: Union[str, PathLike, IO[AnyStr]], params_override: Optional[list] = None, **kwargs, ) -> Run` to solve the following problem:
Load run from YAML file. :param source: The local yaml source of a run. Must be a path to a local file. If the source is a path, it will be open and read. An exception is raised if the file does not exist. :type source: Union[PathLike, str] :param params_override: Fields to overwrite on top of the yaml file. Format is [{"field1": "value1"}, {"field2": "value2"}] :type params_override: List[Dict] :return: A Run object :rtype: Run
Here is the function:
def load_run(
source: Union[str, PathLike, IO[AnyStr]],
params_override: Optional[list] = None,
**kwargs,
) -> Run:
"""Load run from YAML file.
:param source: The local yaml source of a run. Must be a path to a local file.
If the source is a path, it will be open and read.
An exception is raised if the file does not exist.
:type source: Union[PathLike, str]
:param params_override: Fields to overwrite on top of the yaml file.
Format is [{"field1": "value1"}, {"field2": "value2"}]
:type params_override: List[Dict]
:return: A Run object
:rtype: Run
"""
data = load_yaml(source=source)
return Run._load(data=data, yaml_path=source, params_override=params_override, **kwargs) | Load run from YAML file. :param source: The local yaml source of a run. Must be a path to a local file. If the source is a path, it will be open and read. An exception is raised if the file does not exist. :type source: Union[PathLike, str] :param params_override: Fields to overwrite on top of the yaml file. Format is [{"field1": "value1"}, {"field2": "value2"}] :type params_override: List[Dict] :return: A Run object :rtype: Run |
4,172 | from os import PathLike
from pathlib import Path
from typing import IO, AnyStr, Optional, Union
from dotenv import dotenv_values
from .._utils.logger_utils import get_cli_sdk_logger
from .._utils.yaml_utils import load_yaml
from ._errors import MultipleExperimentTemplateError, NoExperimentTemplateError
from .entities import Run
from .entities._connection import CustomConnection, _Connection
from .entities._experiment import Experiment, ExperimentTemplate
from .entities._flow import Flow
def load_common(
cls,
source: Union[str, PathLike, IO[AnyStr]],
relative_origin: str = None,
params_override: Optional[list] = None,
**kwargs,
):
"""Private function to load a yaml file to an entity object.
:param cls: The entity class type.
:type cls: type[Resource]
:param source: A source of yaml.
:type source: Union[str, PathLike, IO[AnyStr]]
:param relative_origin: The origin of to be used when deducing
the relative locations of files referenced in the parsed yaml.
Must be provided, and is assumed to be assigned by other internal
functions that call this.
:type relative_origin: str
:param params_override: _description_, defaults to None
:type params_override: list, optional
"""
if relative_origin is None:
if isinstance(source, (str, PathLike)):
relative_origin = source
else:
try:
relative_origin = source.name
except AttributeError: # input is a stream or something
relative_origin = "./"
params_override = params_override or []
yaml_dict = load_yaml(source)
logger.debug(f"Resolve cls and type with {yaml_dict}, params_override {params_override}.")
# pylint: disable=protected-access
cls, type_str = cls._resolve_cls_and_type(data=yaml_dict, params_override=params_override)
try:
return cls._load(
data=yaml_dict,
yaml_path=relative_origin,
params_override=params_override,
**kwargs,
)
except Exception as e:
raise Exception(f"Load entity error: {e}") from e
def _load_env_to_connection(
source,
params_override: Optional[list] = None,
**kwargs,
):
source = Path(source)
name = next((_dct["name"] for _dct in params_override if "name" in _dct), None)
if not name:
raise Exception("Please specify --name when creating connection from .env.")
if not source.exists():
raise FileNotFoundError(f"File {source.absolute().as_posix()!r} not found.")
try:
data = dict(dotenv_values(source))
if not data:
# Handle some special case dotenv returns empty with no exception raised.
raise ValueError(
f"Load nothing from dotenv file {source.absolute().as_posix()!r}, "
"please make sure the file is not empty and readable."
)
return CustomConnection(name=name, secrets=data)
except Exception as e:
raise Exception(f"Load entity error: {e}") from e
class _Connection(_CoreConnection, YAMLTranslatableMixin):
def _casting_type(cls, typ):
type_dict = {
"azure_open_ai": ConnectionType.AZURE_OPEN_AI.value,
"open_ai": ConnectionType.OPEN_AI.value,
}
if typ in type_dict:
return type_dict.get(typ)
return snake_to_camel(typ)
def _is_scrubbed_value(cls, value):
"""For scrubbed value, cli will get original for update, and prompt user to input for create."""
if value is None or not value:
return True
if all([v == "*" for v in value]):
return True
return value == SCRUBBED_VALUE_NO_CHANGE
def _is_user_input_value(cls, value):
"""The value will prompt user to input in cli for both create and update."""
return value == SCRUBBED_VALUE_USER_INPUT
def _validate_and_encrypt_secrets(self):
encrypt_secrets = {}
invalid_secrets = []
for k, v in self.secrets.items():
# In sdk experience, if v is not scrubbed, use it.
# If v is scrubbed, try to use the value in _secrets.
# If v is <user-input>, raise error.
if self._is_scrubbed_value(v):
# Try to get the value not scrubbed.
v = self._secrets.get(k)
if self._is_scrubbed_value(v) or self._is_user_input_value(v):
# Can't find the original value or is <user-input>, raise error.
invalid_secrets.append(k)
continue
encrypt_secrets[k] = encrypt_secret_value(v)
if invalid_secrets:
raise ValidationException(
f"Connection {self.name!r} secrets {invalid_secrets} value invalid, please fill them."
)
return encrypt_secrets
def _load_from_dict(cls, data: Dict, context: Dict, additional_message: str = None, **kwargs):
schema_cls = cls._get_schema_cls()
try:
loaded_data = schema_cls(context=context).load(data, **kwargs)
except Exception as e:
raise SDKError(f"Load connection failed with {str(e)}. f{(additional_message or '')}.")
return cls(base_path=context[BASE_PATH_CONTEXT_KEY], **loaded_data)
def _to_dict(self) -> Dict:
schema_cls = self._get_schema_cls()
return schema_cls(context={BASE_PATH_CONTEXT_KEY: "./"}).dump(self)
# pylint: disable=unused-argument
def _resolve_cls_and_type(cls, data, params_override=None):
type_in_override = find_type_in_override(params_override)
type_str = type_in_override or data.get("type")
if type_str is None:
raise ValidationException("type is required for connection.")
type_str = cls._casting_type(type_str)
type_cls = _supported_types.get(type_str)
if type_cls is None:
raise ValidationException(
f"connection_type {type_str!r} is not supported. Supported types are: {list(_supported_types.keys())}"
)
return type_cls, type_str
def _to_orm_object(self) -> ORMConnection:
pass
def _from_mt_rest_object(cls, mt_rest_obj) -> "_Connection":
type_cls, _ = cls._resolve_cls_and_type(data={"type": mt_rest_obj.connection_type})
obj = type_cls._from_mt_rest_object(mt_rest_obj)
return obj
def _from_orm_object_with_secrets(cls, orm_object: ORMConnection):
# !!! Attention !!!: Do not use this function to user facing api, use _from_orm_object to remove secrets.
type_cls, _ = cls._resolve_cls_and_type(data={"type": orm_object.connectionType})
obj = type_cls._from_orm_object_with_secrets(orm_object)
return obj
def _from_orm_object(cls, orm_object: ORMConnection):
"""This function will create a connection object then scrub secrets."""
type_cls, _ = cls._resolve_cls_and_type(data={"type": orm_object.connectionType})
obj = type_cls._from_orm_object_with_secrets(orm_object)
# Note: we may can't get secret keys for custom connection from MT
obj.secrets = {k: SCRUBBED_VALUE for k in obj.secrets}
return obj
def _load(
cls,
data: Dict = None,
yaml_path: Union[PathLike, str] = None,
params_override: list = None,
**kwargs,
) -> "_Connection":
"""Load a job object from a yaml file.
:param cls: Indicates that this is a class method.
:type cls: class
:param data: Data Dictionary, defaults to None
:type data: Dict, optional
:param yaml_path: YAML Path, defaults to None
:type yaml_path: Union[PathLike, str], optional
:param params_override: Fields to overwrite on top of the yaml file.
Format is [{"field1": "value1"}, {"field2": "value2"}], defaults to None
:type params_override: List[Dict], optional
:param kwargs: A dictionary of additional configuration parameters.
:type kwargs: dict
:raises Exception: An exception
:return: Loaded job object.
:rtype: Job
"""
data = data or {}
params_override = params_override or []
context = {
BASE_PATH_CONTEXT_KEY: Path(yaml_path).parent if yaml_path else Path("../../azure/_entities/"),
PARAMS_OVERRIDE_KEY: params_override,
}
connection_type, type_str = cls._resolve_cls_and_type(data, params_override)
connection = connection_type._load_from_dict(
data=data,
context=context,
unknown=INCLUDE,
additional_message=f"If you are trying to configure a job that is not of type {type_str}, please specify "
f"the correct connection type in the 'type' property.",
**kwargs,
)
return connection
def _to_execution_connection_dict(self) -> dict:
value = {**self.configs, **self.secrets}
secret_keys = list(self.secrets.keys())
return {
"type": self.class_name, # Required class name for connection in executor
"module": self.module,
"value": {k: v for k, v in value.items() if v is not None}, # Filter None value out
"secret_keys": secret_keys,
}
def _from_execution_connection_dict(cls, name, data) -> "_Connection":
type_cls, _ = cls._resolve_cls_and_type(data={"type": data.get("type")[: -len("Connection")]})
value_dict = data.get("value", {})
if type_cls == CustomConnection:
secrets = {k: v for k, v in value_dict.items() if k in data.get("secret_keys", [])}
configs = {k: v for k, v in value_dict.items() if k not in secrets}
return CustomConnection(name=name, configs=configs, secrets=secrets)
return type_cls(name=name, **value_dict)
def _get_scrubbed_secrets(self):
"""Return the scrubbed secrets of connection."""
return {key: val for key, val in self.secrets.items() if self._is_scrubbed_value(val)}
The provided code snippet includes necessary dependencies for implementing the `load_connection` function. Write a Python function `def load_connection( source: Union[str, PathLike, IO[AnyStr]], **kwargs, )` to solve the following problem:
Load connection from YAML file or .env file. :param source: The local yaml source of a connection or .env file. Must be a path to a local file. If the source is a path, it will be open and read. An exception is raised if the file does not exist. :type source: Union[PathLike, str] :return: A Connection object :rtype: Connection
Here is the function:
def load_connection(
source: Union[str, PathLike, IO[AnyStr]],
**kwargs,
):
"""Load connection from YAML file or .env file.
:param source: The local yaml source of a connection or .env file. Must be a path to a local file.
If the source is a path, it will be open and read.
An exception is raised if the file does not exist.
:type source: Union[PathLike, str]
:return: A Connection object
:rtype: Connection
"""
if Path(source).name.endswith(".env"):
return _load_env_to_connection(source, **kwargs)
return load_common(_Connection, source, **kwargs) | Load connection from YAML file or .env file. :param source: The local yaml source of a connection or .env file. Must be a path to a local file. If the source is a path, it will be open and read. An exception is raised if the file does not exist. :type source: Union[PathLike, str] :return: A Connection object :rtype: Connection |
4,173 | from os import PathLike
from pathlib import Path
from typing import IO, AnyStr, Optional, Union
from dotenv import dotenv_values
from .._utils.logger_utils import get_cli_sdk_logger
from .._utils.yaml_utils import load_yaml
from ._errors import MultipleExperimentTemplateError, NoExperimentTemplateError
from .entities import Run
from .entities._connection import CustomConnection, _Connection
from .entities._experiment import Experiment, ExperimentTemplate
from .entities._flow import Flow
def load_common(
cls,
source: Union[str, PathLike, IO[AnyStr]],
relative_origin: str = None,
params_override: Optional[list] = None,
**kwargs,
):
"""Private function to load a yaml file to an entity object.
:param cls: The entity class type.
:type cls: type[Resource]
:param source: A source of yaml.
:type source: Union[str, PathLike, IO[AnyStr]]
:param relative_origin: The origin of to be used when deducing
the relative locations of files referenced in the parsed yaml.
Must be provided, and is assumed to be assigned by other internal
functions that call this.
:type relative_origin: str
:param params_override: _description_, defaults to None
:type params_override: list, optional
"""
if relative_origin is None:
if isinstance(source, (str, PathLike)):
relative_origin = source
else:
try:
relative_origin = source.name
except AttributeError: # input is a stream or something
relative_origin = "./"
params_override = params_override or []
yaml_dict = load_yaml(source)
logger.debug(f"Resolve cls and type with {yaml_dict}, params_override {params_override}.")
# pylint: disable=protected-access
cls, type_str = cls._resolve_cls_and_type(data=yaml_dict, params_override=params_override)
try:
return cls._load(
data=yaml_dict,
yaml_path=relative_origin,
params_override=params_override,
**kwargs,
)
except Exception as e:
raise Exception(f"Load entity error: {e}") from e
class MultipleExperimentTemplateError(SDKError):
"""Exception raised if multiple experiment template yaml found."""
pass
class NoExperimentTemplateError(SDKError):
"""Exception raised if no experiment template yaml found."""
pass
class ExperimentTemplate(YAMLTranslatableMixin, SchemaValidatableMixin):
def __init__(self, nodes, description=None, data=None, inputs=None, **kwargs):
self._base_path = kwargs.get(BASE_PATH_CONTEXT_KEY, Path("."))
self.dir_name = self._get_directory_name()
self.description = description
self.nodes = nodes
self.data = data or []
self.inputs = inputs or []
self._source_path = None
# pylint: disable=unused-argument
def _resolve_cls_and_type(cls, **kwargs):
return cls, "experiment_template"
def _get_schema_cls(cls):
return ExperimentTemplateSchema
def _load(
cls,
data: Optional[Dict] = None,
yaml_path: Optional[Union[PathLike, str]] = None,
params_override: Optional[list] = None,
**kwargs,
):
data = data or {}
params_override = params_override or []
context = {
BASE_PATH_CONTEXT_KEY: Path(yaml_path).parent if yaml_path else Path("./"),
PARAMS_OVERRIDE_KEY: params_override,
}
logger.debug(f"Loading class object with data {data}, params_override {params_override}, context {context}.")
exp = cls._load_from_dict(
data=data,
context=context,
additional_message="Failed to load experiment",
**kwargs,
)
if yaml_path:
exp._source_path = yaml_path
return exp
def _get_directory_name(self) -> str:
"""Get experiment template directory name."""
try:
folder_name = Path(self._base_path).resolve().absolute().name
return folder_name
except Exception as e:
logger.debug(f"Failed to generate template name, error: {e}, use uuid.")
return str(uuid.uuid4())
def _load_from_dict(cls, data: Dict, context: Dict, additional_message: str = None, **kwargs):
schema_cls = cls._get_schema_cls()
try:
loaded_data = schema_cls(context=context).load(data, **kwargs)
except Exception as e:
raise Exception(f"Load experiment template failed with {str(e)}. f{(additional_message or '')}.")
return cls(base_path=context[BASE_PATH_CONTEXT_KEY], **loaded_data)
def _create_schema_for_validation(cls, context) -> Schema:
return cls._get_schema_cls()(context=context)
def _default_context(self) -> dict:
return {BASE_PATH_CONTEXT_KEY: self._base_path}
def _create_validation_error(cls, message: str, no_personal_data_message: str) -> Exception:
return ExperimentValidationError(
message=message,
no_personal_data_message=no_personal_data_message,
)
def _customized_validate(self) -> MutableValidationResult:
"""Validate the resource with customized logic.
Override this method to add customized validation logic.
:return: The customized validation result
:rtype: MutableValidationResult
"""
pass
The provided code snippet includes necessary dependencies for implementing the `_load_experiment_template` function. Write a Python function `def _load_experiment_template( source: Union[str, PathLike, IO[AnyStr]], **kwargs, )` to solve the following problem:
Load experiment template from YAML file. :param source: The local yaml source of an experiment template. Must be a path to a local file. If the source is a path, it will be open and read. An exception is raised if the file does not exist. :type source: Union[PathLike, str] :return: An ExperimentTemplate object :rtype: ExperimentTemplate
Here is the function:
def _load_experiment_template(
source: Union[str, PathLike, IO[AnyStr]],
**kwargs,
):
"""Load experiment template from YAML file.
:param source: The local yaml source of an experiment template. Must be a path to a local file.
If the source is a path, it will be open and read.
An exception is raised if the file does not exist.
:type source: Union[PathLike, str]
:return: An ExperimentTemplate object
:rtype: ExperimentTemplate
"""
source_path = Path(source)
if source_path.is_dir():
target_yaml_list = []
for item in list(source_path.iterdir()):
if item.name.endswith(".exp.yaml"):
target_yaml_list.append(item)
if len(target_yaml_list) > 1:
raise MultipleExperimentTemplateError(
f"Multiple experiment template files found in {source_path.resolve().absolute().as_posix()}, "
f"please specify one."
)
if not target_yaml_list:
raise NoExperimentTemplateError(
f"Experiment template file not found in {source_path.resolve().absolute().as_posix()}."
)
source_path = target_yaml_list[0]
if not source_path.exists():
raise NoExperimentTemplateError(
f"Experiment template file {source_path.resolve().absolute().as_posix()} not found."
)
return load_common(ExperimentTemplate, source=source_path) | Load experiment template from YAML file. :param source: The local yaml source of an experiment template. Must be a path to a local file. If the source is a path, it will be open and read. An exception is raised if the file does not exist. :type source: Union[PathLike, str] :return: An ExperimentTemplate object :rtype: ExperimentTemplate |
4,174 | from os import PathLike
from pathlib import Path
from typing import IO, AnyStr, Optional, Union
from dotenv import dotenv_values
from .._utils.logger_utils import get_cli_sdk_logger
from .._utils.yaml_utils import load_yaml
from ._errors import MultipleExperimentTemplateError, NoExperimentTemplateError
from .entities import Run
from .entities._connection import CustomConnection, _Connection
from .entities._experiment import Experiment, ExperimentTemplate
from .entities._flow import Flow
def load_common(
cls,
source: Union[str, PathLike, IO[AnyStr]],
relative_origin: str = None,
params_override: Optional[list] = None,
**kwargs,
):
"""Private function to load a yaml file to an entity object.
:param cls: The entity class type.
:type cls: type[Resource]
:param source: A source of yaml.
:type source: Union[str, PathLike, IO[AnyStr]]
:param relative_origin: The origin of to be used when deducing
the relative locations of files referenced in the parsed yaml.
Must be provided, and is assumed to be assigned by other internal
functions that call this.
:type relative_origin: str
:param params_override: _description_, defaults to None
:type params_override: list, optional
"""
if relative_origin is None:
if isinstance(source, (str, PathLike)):
relative_origin = source
else:
try:
relative_origin = source.name
except AttributeError: # input is a stream or something
relative_origin = "./"
params_override = params_override or []
yaml_dict = load_yaml(source)
logger.debug(f"Resolve cls and type with {yaml_dict}, params_override {params_override}.")
# pylint: disable=protected-access
cls, type_str = cls._resolve_cls_and_type(data=yaml_dict, params_override=params_override)
try:
return cls._load(
data=yaml_dict,
yaml_path=relative_origin,
params_override=params_override,
**kwargs,
)
except Exception as e:
raise Exception(f"Load entity error: {e}") from e
class NoExperimentTemplateError(SDKError):
"""Exception raised if no experiment template yaml found."""
pass
class Experiment(ExperimentTemplate):
def __init__(
self,
nodes,
name=None,
data=None,
inputs=None,
status=ExperimentStatus.NOT_STARTED,
node_runs=None,
properties=None,
**kwargs,
):
self.name = name or self._generate_name()
self.status = status
self.node_runs = node_runs or {}
self.properties = properties or {}
self.created_on = kwargs.get("created_on", datetime.datetime.now().isoformat())
self.last_start_time = kwargs.get("last_start_time", None)
self.last_end_time = kwargs.get("last_end_time", None)
self.is_archived = kwargs.get("is_archived", False)
self._output_dir = HOME_PROMPT_FLOW_DIR / PROMPT_FLOW_EXP_DIR_NAME / self.name
super().__init__(nodes, name=self.name, data=data, inputs=inputs, **kwargs)
def _get_schema_cls(cls):
return ExperimentSchema
# pylint: disable=unused-argument
def _resolve_cls_and_type(cls, **kwargs):
return cls, "experiment"
def _generate_name(self) -> str:
"""Generate a experiment name."""
try:
folder_name = Path(self._base_path).resolve().absolute().name
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S_%f")
exp_name = f"{folder_name}_{timestamp}"
return _sanitize_python_variable_name(exp_name)
except Exception as e:
logger.debug(f"Failed to generate experiment name, error: {e}, use uuid.")
return str(uuid.uuid4())
def _save_snapshot_and_update_node(
self,
):
"""Save node source to experiment snapshot, update node path."""
snapshot_dir = self._output_dir / "snapshots"
for node in self.nodes:
node._save_snapshot(snapshot_dir)
def _append_node_run(self, node_name, run: Run):
"""Append node run to experiment."""
if node_name not in self.node_runs or not isinstance(self.node_runs[node_name], list):
self.node_runs[node_name] = []
# TODO: Review this
self.node_runs[node_name].append({"name": run.name, "status": run.status})
def _to_orm_object(self):
"""Convert to ORM object."""
result = ORMExperiment(
name=self.name,
description=self.description,
status=self.status,
created_on=self.created_on,
archived=self.is_archived,
last_start_time=self.last_start_time,
last_end_time=self.last_end_time,
properties=json.dumps(self.properties),
data=json.dumps([item._to_dict() for item in self.data]),
inputs=json.dumps([input._to_dict() for input in self.inputs]),
nodes=json.dumps([node._to_dict() for node in self.nodes]),
node_runs=json.dumps(self.node_runs),
)
logger.debug(f"Experiment to ORM object: {result.__dict__}")
return result
def _from_orm_object(cls, obj: ORMExperiment) -> "Experiment":
"""Create a experiment object from ORM object."""
nodes = []
context = {BASE_PATH_CONTEXT_KEY: "./"}
for node_dict in json.loads(obj.nodes):
if node_dict["type"] == ExperimentNodeType.FLOW:
nodes.append(
FlowNode._load_from_dict(node_dict, context=context, additional_message="Failed to load node.")
)
elif node_dict["type"] == ExperimentNodeType.COMMAND:
nodes.append(
CommandNode._load_from_dict(node_dict, context=context, additional_message="Failed to load node.")
)
else:
raise Exception(f"Unknown node type {node_dict['type']}")
data = [
ExperimentData._load_from_dict(item, context=context, additional_message="Failed to load experiment data")
for item in json.loads(obj.data)
]
inputs = [
ExperimentInput._load_from_dict(
item, context=context, additional_message="Failed to load experiment inputs"
)
for item in json.loads(obj.inputs)
]
return cls(
name=obj.name,
description=obj.description,
status=obj.status,
created_on=obj.created_on,
last_start_time=obj.last_start_time,
last_end_time=obj.last_end_time,
is_archived=obj.archived,
properties=json.loads(obj.properties),
data=data,
inputs=inputs,
nodes=nodes,
node_runs=json.loads(obj.node_runs),
)
def from_template(cls, template: ExperimentTemplate, name=None):
"""Create a experiment object from template."""
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S_%f")
exp_name = name or f"{template.dir_name}_{timestamp}"
experiment = cls(
name=exp_name,
description=template.description,
data=copy.deepcopy(template.data),
inputs=copy.deepcopy(template.inputs),
nodes=copy.deepcopy(template.nodes),
base_path=template._base_path,
)
logger.debug("Start saving snapshot and update node.")
experiment._save_snapshot_and_update_node()
return experiment
The provided code snippet includes necessary dependencies for implementing the `_load_experiment` function. Write a Python function `def _load_experiment( source: Union[str, PathLike, IO[AnyStr]], **kwargs, )` to solve the following problem:
Load experiment from YAML file. :param source: The local yaml source of an experiment. Must be a path to a local file. If the source is a path, it will be open and read. An exception is raised if the file does not exist. :type source: Union[PathLike, str] :return: An Experiment object :rtype: Experiment
Here is the function:
def _load_experiment(
source: Union[str, PathLike, IO[AnyStr]],
**kwargs,
):
"""
Load experiment from YAML file.
:param source: The local yaml source of an experiment. Must be a path to a local file.
If the source is a path, it will be open and read.
An exception is raised if the file does not exist.
:type source: Union[PathLike, str]
:return: An Experiment object
:rtype: Experiment
"""
source = Path(source)
absolute_path = source.resolve().absolute().as_posix()
if not source.exists():
raise NoExperimentTemplateError(f"Experiment file {absolute_path} not found.")
experiment = load_common(Experiment, source, **kwargs)
return experiment | Load experiment from YAML file. :param source: The local yaml source of an experiment. Must be a path to a local file. If the source is a path, it will be open and read. An exception is raised if the file does not exist. :type source: Union[PathLike, str] :return: An Experiment object :rtype: Experiment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.