code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def wait(self): """ Wait for the run to finish, returning True if the run succeeded and false otherwise. Note that in some cases (e.g. remote execution on Databricks), we may wait until the remote job completes rather than until the MLflow run completes. """
Wait for the run to finish, returning True if the run succeeded and false otherwise. Note that in some cases (e.g. remote execution on Databricks), we may wait until the remote job completes rather than until the MLflow run completes.
wait
python
mlflow/mlflow
mlflow/projects/submitted_run.py
https://github.com/mlflow/mlflow/blob/master/mlflow/projects/submitted_run.py
Apache-2.0
def cancel(self): """ Cancel the run (interrupts the command subprocess, cancels the Databricks run, etc) and waits for it to terminate. The MLflow run status may not be set correctly upon run cancellation. """
Cancel the run (interrupts the command subprocess, cancels the Databricks run, etc) and waits for it to terminate. The MLflow run status may not be set correctly upon run cancellation.
cancel
python
mlflow/mlflow
mlflow/projects/submitted_run.py
https://github.com/mlflow/mlflow/blob/master/mlflow/projects/submitted_run.py
Apache-2.0
def _is_git_repo(path) -> bool: """Returns True if passed-in path is a valid git repository""" import git try: repo = git.Repo(path) if len(repo.branches) > 0: return True except git.exc.InvalidGitRepositoryError: pass return False
Returns True if passed-in path is a valid git repository
_is_git_repo
python
mlflow/mlflow
mlflow/projects/utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/projects/utils.py
Apache-2.0
def _parse_file_uri(uri: str) -> str: """Converts file URIs to filesystem paths""" if _is_file_uri(uri): parsed_file_uri = urllib.parse.urlparse(uri) return str( pathlib.Path(parsed_file_uri.netloc, parsed_file_uri.path, parsed_file_uri.fragment) ) return uri
Converts file URIs to filesystem paths
_parse_file_uri
python
mlflow/mlflow
mlflow/projects/utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/projects/utils.py
Apache-2.0
def _is_valid_branch_name(work_dir, version): """ Returns True if the ``version`` is the name of a branch in a Git project. ``work_dir`` must be the working directory in a git repo. """ if version is not None: from git import Repo from git.exc import GitCommandError repo = R...
Returns True if the ``version`` is the name of a branch in a Git project. ``work_dir`` must be the working directory in a git repo.
_is_valid_branch_name
python
mlflow/mlflow
mlflow/projects/utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/projects/utils.py
Apache-2.0
def _fetch_project(uri, version=None): """ Fetch a project into a local directory, returning the path to the local project directory. """ parsed_uri, subdirectory = _parse_subdirectory(uri) use_temp_dst_dir = _is_zip_uri(parsed_uri) or not _is_local_uri(parsed_uri) dst_dir = tempfile.mkdtemp() i...
Fetch a project into a local directory, returning the path to the local project directory.
_fetch_project
python
mlflow/mlflow
mlflow/projects/utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/projects/utils.py
Apache-2.0
def _create_run(uri, experiment_id, work_dir, version, entry_point, parameters): """ Create a ``Run`` against the current MLflow tracking server, logging metadata (e.g. the URI, entry point, and parameters of the project) about the run. Return an ``ActiveRun`` that can be used to report additional data ...
Create a ``Run`` against the current MLflow tracking server, logging metadata (e.g. the URI, entry point, and parameters of the project) about the run. Return an ``ActiveRun`` that can be used to report additional data about the run (metrics/params) to the tracking server.
_create_run
python
mlflow/mlflow
mlflow/projects/utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/projects/utils.py
Apache-2.0
def get_entry_point_command(project, entry_point, parameters, storage_dir): """ Returns the shell command to execute in order to run the specified entry point. Args: project: Project containing the target entry point. entry_point: Entry point to run. parameters: Parameters (dictiona...
Returns the shell command to execute in order to run the specified entry point. Args: project: Project containing the target entry point. entry_point: Entry point to run. parameters: Parameters (dictionary) for the entry point command. storage_dir: Base local directory to use f...
get_entry_point_command
python
mlflow/mlflow
mlflow/projects/utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/projects/utils.py
Apache-2.0
def get_run_env_vars(run_id, experiment_id): """ Returns a dictionary of environment variable key-value pairs to set in subprocess launched to run MLflow projects. """ return { MLFLOW_RUN_ID.name: run_id, MLFLOW_TRACKING_URI.name: tracking.get_tracking_uri(), MLFLOW_EXPERIMEN...
Returns a dictionary of environment variable key-value pairs to set in subprocess launched to run MLflow projects.
get_run_env_vars
python
mlflow/mlflow
mlflow/projects/utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/projects/utils.py
Apache-2.0
def compute_parameters(self, user_parameters, storage_dir): """ Given a dict mapping user-specified param names to values, computes parameters to substitute into the command for this entry point. Returns a tuple (params, extra_params) where `params` contains key-value pairs for parameter...
Given a dict mapping user-specified param names to values, computes parameters to substitute into the command for this entry point. Returns a tuple (params, extra_params) where `params` contains key-value pairs for parameters specified in the entry point definition, and `extra_params` c...
compute_parameters
python
mlflow/mlflow
mlflow/projects/_project_spec.py
https://github.com/mlflow/mlflow/blob/master/mlflow/projects/_project_spec.py
Apache-2.0
def _resolve_experiment_id(experiment_name=None, experiment_id=None): """ Resolve experiment. Verifies either one or other is specified - cannot be both selected. If ``experiment_name`` is provided and does not exist, an experiment of that name is created and its id is returned. Args: ...
Resolve experiment. Verifies either one or other is specified - cannot be both selected. If ``experiment_name`` is provided and does not exist, an experiment of that name is created and its id is returned. Args: experiment_name: Name of experiment under which to launch the run. e...
_resolve_experiment_id
python
mlflow/mlflow
mlflow/projects/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/projects/__init__.py
Apache-2.0
def _maybe_set_run_terminated(active_run, status): """ If the passed-in active run is defined and still running (i.e. hasn't already been terminated within user code), mark it as terminated with the passed-in status. """ if active_run is None: return run_id = active_run.info.run_id c...
If the passed-in active run is defined and still running (i.e. hasn't already been terminated within user code), mark it as terminated with the passed-in status.
_maybe_set_run_terminated
python
mlflow/mlflow
mlflow/projects/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/projects/__init__.py
Apache-2.0
def _build_mlflow_run_cmd( uri, entry_point, docker_args, storage_dir, env_manager, run_id, parameters ): """ Build and return an array containing an ``mlflow run`` command that can be invoked to locally run the project at the specified URI. """ mlflow_run_arr = ["mlflow", "run", uri, "-e", entr...
Build and return an array containing an ``mlflow run`` command that can be invoked to locally run the project at the specified URI.
_build_mlflow_run_cmd
python
mlflow/mlflow
mlflow/projects/backend/local.py
https://github.com/mlflow/mlflow/blob/master/mlflow/projects/backend/local.py
Apache-2.0
def _run_mlflow_run_cmd(mlflow_run_arr, env_map): """ Invoke ``mlflow run`` in a subprocess, which in turn runs the entry point in a child process. Returns a handle to the subprocess. Popen launched to invoke ``mlflow run``. """ final_env = os.environ.copy() final_env.update(env_map) # Launc...
Invoke ``mlflow run`` in a subprocess, which in turn runs the entry point in a child process. Returns a handle to the subprocess. Popen launched to invoke ``mlflow run``.
_run_mlflow_run_cmd
python
mlflow/mlflow
mlflow/projects/backend/local.py
https://github.com/mlflow/mlflow/blob/master/mlflow/projects/backend/local.py
Apache-2.0
def model_version_to_prompt_version( model_version: ModelVersion, prompt_tags: Optional[dict[str, str]] = None ) -> PromptVersion: """ Create a PromptVersion object from a ModelVersion object. Args: model_version: The ModelVersion object to convert to a PromptVersion. prompt_tags: The p...
Create a PromptVersion object from a ModelVersion object. Args: model_version: The ModelVersion object to convert to a PromptVersion. prompt_tags: The prompt-level tags. Optional. Returns: PromptVersion: The converted PromptVersion object.
model_version_to_prompt_version
python
mlflow/mlflow
mlflow/prompt/registry_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/prompt/registry_utils.py
Apache-2.0
def add_prompt_filter_string( filter_string: Optional[str], is_prompt: bool = False ) -> Optional[str]: """ Additional filter string to include/exclude prompts from the result. By default, exclude prompts from the result. """ if IS_PROMPT_TAG_KEY not in (filter_string or ""): prompt_filt...
Additional filter string to include/exclude prompts from the result. By default, exclude prompts from the result.
add_prompt_filter_string
python
mlflow/mlflow
mlflow/prompt/registry_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/prompt/registry_utils.py
Apache-2.0
def has_prompt_tag(tags: Optional[Union[list[RegisteredModelTag], dict[str, str]]]) -> bool: """Check if the given tags contain the prompt tag.""" if isinstance(tags, dict): return IS_PROMPT_TAG_KEY in tags if tags else False if not tags: return return any(tag.key == IS_PROMPT_TAG_KEY fo...
Check if the given tags contain the prompt tag.
has_prompt_tag
python
mlflow/mlflow
mlflow/prompt/registry_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/prompt/registry_utils.py
Apache-2.0
def is_prompt_supported_registry(registry_uri: Optional[str] = None) -> bool: """ Check if the current registry supports prompts. Prompts registration is supported in: - OSS MLflow Tracking Server (always) - Unity Catalog - Not supported in legacy Databricks workspace registry or Unity Catalog ...
Check if the current registry supports prompts. Prompts registration is supported in: - OSS MLflow Tracking Server (always) - Unity Catalog - Not supported in legacy Databricks workspace registry or Unity Catalog OSS
is_prompt_supported_registry
python
mlflow/mlflow
mlflow/prompt/registry_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/prompt/registry_utils.py
Apache-2.0
def require_prompt_registry(func): """Ensure that the current registry supports prompts.""" @functools.wraps(func) def wrapper(*args, **kwargs): if args and isinstance(args[0], mlflow.MlflowClient): registry_uri = args[0]._registry_uri else: registry_uri = mlflow.get...
Ensure that the current registry supports prompts.
require_prompt_registry
python
mlflow/mlflow
mlflow/prompt/registry_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/prompt/registry_utils.py
Apache-2.0
def translate_prompt_exception(func): """ Translate MlflowException message related to RegisteredModel / ModelVersion into prompt-specific message. """ MODEL_PATTERN = re.compile(r"(registered model|model version)", re.IGNORECASE) @functools.wraps(func) def wrapper(*args, **kwargs): ...
Translate MlflowException message related to RegisteredModel / ModelVersion into prompt-specific message.
translate_prompt_exception
python
mlflow/mlflow
mlflow/prompt/registry_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/prompt/registry_utils.py
Apache-2.0
def validate_prompt_name(name: Any): """Validate the prompt name against the prompt specific rule""" if not isinstance(name, str) or not name: raise MlflowException.invalid_parameter_value( "Prompt name must be a non-empty string.", ) if PROMPT_NAME_RULE.match(name) is None: ...
Validate the prompt name against the prompt specific rule
validate_prompt_name
python
mlflow/mlflow
mlflow/prompt/registry_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/prompt/registry_utils.py
Apache-2.0
def handle_resource_already_exist_error( name: str, is_existing_entity_prompt: bool, is_new_entity_prompt: bool, ): """ Show a more specific error message for name conflict in Model Registry. 1. When creating a model with the same name as an existing model, say "model already exists". 2. Wh...
Show a more specific error message for name conflict in Model Registry. 1. When creating a model with the same name as an existing model, say "model already exists". 2. When creating a prompt with the same name as an existing prompt, say "prompt already exists". 3. Otherwise, explain that a prompt and...
handle_resource_already_exist_error
python
mlflow/mlflow
mlflow/prompt/registry_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/prompt/registry_utils.py
Apache-2.0
def parse_prompt_name_or_uri( name_or_uri: str, version: Optional[Union[str, int]] = None ) -> tuple[str, Optional[Union[str, int]]]: """ Parse prompt name or URI into (name, version) tuple. Handles two cases: 1. URI format: "prompts:/name/version" or "prompts:/name@alias" - Returns (name, p...
Parse prompt name or URI into (name, version) tuple. Handles two cases: 1. URI format: "prompts:/name/version" or "prompts:/name@alias" - Returns (name, parsed_version) - Raises error if version parameter is also provided 2. Name format: "my_prompt" - Returns (name, version) ...
parse_prompt_name_or_uri
python
mlflow/mlflow
mlflow/prompt/registry_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/prompt/registry_utils.py
Apache-2.0
def log_model( model, artifact_path: Optional[str] = None, conda_env=None, code_paths=None, registered_model_name=None, signature=None, input_example=None, await_registration_for=DEFAULT_AWAIT_MAX_SLEEP_SECONDS, pip_requirements=None, extra_pip_requirements=None, metadata=Non...
Log a Promptflow model as an MLflow artifact for the current run. Args: model: A promptflow model loaded by `promptflow.load_flow()`. artifact_path: Deprecated. Use `name` instead. conda_env: {{ conda_env }} code_paths: {{ code_paths }} registered_model_name: If given, ...
log_model
python
mlflow/mlflow
mlflow/promptflow/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/promptflow/__init__.py
Apache-2.0
def save_model( model, path, conda_env=None, code_paths=None, mlflow_model=None, signature: ModelSignature = None, input_example: ModelInputExample = None, pip_requirements=None, extra_pip_requirements=None, metadata=None, model_config: Optional[dict[str, Any]] = None, ): ...
Save a Promptflow model to a path on the local file system. Args: model: A promptflow model loaded by `promptflow.load_flow()`. path: Local path where the serialized model (as YAML) is to be saved. conda_env: {{ conda_env }} code_paths: {{ code_paths }} mlflow_model: :p...
save_model
python
mlflow/mlflow
mlflow/promptflow/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/promptflow/__init__.py
Apache-2.0
def predict( # pylint: disable=unused-argument self, data: Union[pd.DataFrame, list[Union[str, dict[str, Any]]]], params: Optional[dict[str, Any]] = None, # pylint: disable=unused-argument ) -> Union[dict, list]: """ Args: data: Model input data. Either a pandas...
Args: data: Model input data. Either a pandas DataFrame with only 1 row or a dictionary. .. code-block:: python loaded_model = mlflow.pyfunc.load_model(logged_model.model_uri) # Predict on a flow input dictionary. ...
predict
python
mlflow/mlflow
mlflow/promptflow/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/promptflow/__init__.py
Apache-2.0
def _load_pyfunc(path, model_config: Optional[dict[str, Any]] = None): # noqa: D417 """ Load PyFunc implementation for Promptflow. Called by ``pyfunc.load_model``. Args path: Local filesystem path to the MLflow Model with the ``promptflow`` flavor. """ from promptflow import load_flow ...
Load PyFunc implementation for Promptflow. Called by ``pyfunc.load_model``. Args path: Local filesystem path to the MLflow Model with the ``promptflow`` flavor.
_load_pyfunc
python
mlflow/mlflow
mlflow/promptflow/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/promptflow/__init__.py
Apache-2.0
def load_model(model_uri, dst_path=None): """ Load a Promptflow model from a local file or a run. Args: model_uri: The location, in URI format, of the MLflow model. For example: - ``/Users/me/path/to/local/model`` - ``relative/path/to/local/model`` - ``s3://my_b...
Load a Promptflow model from a local file or a run. Args: model_uri: The location, in URI format, of the MLflow model. For example: - ``/Users/me/path/to/local/model`` - ``relative/path/to/local/model`` - ``s3://my_bucket/path/to/model`` - ``runs:/<mlfl...
load_model
python
mlflow/mlflow
mlflow/promptflow/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/promptflow/__init__.py
Apache-2.0
def load_model(model_uri, dst_path=None): """ Load a Prophet model from a local file or a run. Args: model_uri: The location, in URI format, of the MLflow model. For example: - ``/Users/me/path/to/local/model`` - ``relative/path/to/local/model`` - ``s3://my_buck...
Load a Prophet model from a local file or a run. Args: model_uri: The location, in URI format, of the MLflow model. For example: - ``/Users/me/path/to/local/model`` - ``relative/path/to/local/model`` - ``s3://my_bucket/path/to/model`` - ``runs:/<mlflow_...
load_model
python
mlflow/mlflow
mlflow/prophet/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/prophet/__init__.py
Apache-2.0
def autolog(log_traces: bool = True, disable: bool = False, silent: bool = False): """ Enable (or disable) autologging for Pydantic_AI. Args: log_traces: If True, capture spans for agent + model calls. disable: If True, disable the autologging patches. silent: If True, suppress...
Enable (or disable) autologging for Pydantic_AI. Args: log_traces: If True, capture spans for agent + model calls. disable: If True, disable the autologging patches. silent: If True, suppress MLflow warnings/info.
autolog
python
mlflow/mlflow
mlflow/pydantic_ai/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pydantic_ai/__init__.py
Apache-2.0
def __init__( # noqa: D417 self, config, env_manager, workers=1, install_mlflow=False, create_env_root_dir=False, env_root_dir=None, **kwargs, ): """ Args: env_manager: Environment manager to use for preparing the environme...
Args: env_manager: Environment manager to use for preparing the environment. If None, MLflow will automatically pick the env manager based on the model's flavor configuration for generate_dockerfile. It can't be None for other methods. env_root_dir: Root ...
__init__
python
mlflow/mlflow
mlflow/pyfunc/backend.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/backend.py
Apache-2.0
def predict( self, model_uri, input_path, output_path, content_type, pip_requirements_override=None, extra_envs=None, ): """ Generate predictions using generic python model saved with MLflow. The expected format of the input JSON is the...
Generate predictions using generic python model saved with MLflow. The expected format of the input JSON is the MLflow scoring format. Return the prediction results as a JSON.
predict
python
mlflow/mlflow
mlflow/pyfunc/backend.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/backend.py
Apache-2.0
def setup_sigterm_on_parent_death(): """ Uses prctl to automatically send SIGTERM to the command process when its parent is dead. This handles the case when the parent is a PySpark worker process. If a user cancels the PySpark job, the wor...
Uses prctl to automatically send SIGTERM to the command process when its parent is dead. This handles the case when the parent is a PySpark worker process. If a user cancels the PySpark job, the worker process gets killed, regardless of P...
setup_sigterm_on_parent_death
python
mlflow/mlflow
mlflow/pyfunc/backend.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/backend.py
Apache-2.0
def _get_base_image(self, model_path: str, install_java: bool) -> str: """ Determine the base image to use for the Dockerfile. We use Python slim base image when all the following conditions are met: 1. Model URI is specified by the user 2. Model flavor does not require Java...
Determine the base image to use for the Dockerfile. We use Python slim base image when all the following conditions are met: 1. Model URI is specified by the user 2. Model flavor does not require Java 3. Python version is specified in the model Returns: ...
_get_base_image
python
mlflow/mlflow
mlflow/pyfunc/backend.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/backend.py
Apache-2.0
def set_prediction_context(context: Optional[Context]): """ Set the context for the current prediction request. The context will be set as a thread-local variable and will be accessible globally within the same thread. Args: context: The context for the current prediction request. """ i...
Set the context for the current prediction request. The context will be set as a thread-local variable and will be accessible globally within the same thread. Args: context: The context for the current prediction request.
set_prediction_context
python
mlflow/mlflow
mlflow/pyfunc/context.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/context.py
Apache-2.0
def __getstate__(self): """ The `DBConnectArtifactCache` instance is created in Databricks Connect client side, and it will be pickled to Databricks Connect UDF sandbox (see `get_unpacked_artifact_dir` method), but Spark Connect client object is not pickle-able, we need to skip t...
The `DBConnectArtifactCache` instance is created in Databricks Connect client side, and it will be pickled to Databricks Connect UDF sandbox (see `get_unpacked_artifact_dir` method), but Spark Connect client object is not pickle-able, we need to skip this field.
__getstate__
python
mlflow/mlflow
mlflow/pyfunc/dbconnect_artifact_cache.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/dbconnect_artifact_cache.py
Apache-2.0
def add_artifact_archive(self, cache_key, artifact_archive_path): """ Add an artifact archive file to Databricks connect cache. The archive file must be 'tar.gz' format. You can only call this method in Databricks Connect client side. """ if not artifact_archive_path.ends...
Add an artifact archive file to Databricks connect cache. The archive file must be 'tar.gz' format. You can only call this method in Databricks Connect client side.
add_artifact_archive
python
mlflow/mlflow
mlflow/pyfunc/dbconnect_artifact_cache.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/dbconnect_artifact_cache.py
Apache-2.0
def get_unpacked_artifact_dir(self, cache_key): """ Get unpacked artifact directory path, you can only call this method inside Databricks Connect spark UDF sandbox. """ if cache_key not in self._cache: raise RuntimeError(f"The artifact '{cache_key}' does not exist.") ...
Get unpacked artifact directory path, you can only call this method inside Databricks Connect spark UDF sandbox.
get_unpacked_artifact_dir
python
mlflow/mlflow
mlflow/pyfunc/dbconnect_artifact_cache.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/dbconnect_artifact_cache.py
Apache-2.0
def archive_directory(input_dir, archive_file_path): """ Archive the `input_dir` directory, save the archive file to `archive_file_path`, the generated archive file is 'tar.gz' format. Note: all symlink files in the input directory are kept as it is in the archive file. """ archive_file_path = ...
Archive the `input_dir` directory, save the archive file to `archive_file_path`, the generated archive file is 'tar.gz' format. Note: all symlink files in the input directory are kept as it is in the archive file.
archive_directory
python
mlflow/mlflow
mlflow/pyfunc/dbconnect_artifact_cache.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/dbconnect_artifact_cache.py
Apache-2.0
def load_context(self, context): """ Loads artifacts from the specified :class:`~PythonModelContext` that can be used by :func:`~PythonModel.predict` when evaluating inputs. When loading an MLflow model with :func:`~load_model`, this method is called as soon as the :class:`~PythonModel` ...
Loads artifacts from the specified :class:`~PythonModelContext` that can be used by :func:`~PythonModel.predict` when evaluating inputs. When loading an MLflow model with :func:`~load_model`, this method is called as soon as the :class:`~PythonModel` is constructed. The same :c...
load_context
python
mlflow/mlflow
mlflow/pyfunc/model.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/model.py
Apache-2.0
def predict_type_hints(self) -> _TypeHints: """ Internal method to get type hints from the predict function signature. """ if hasattr(self, "_predict_type_hints"): return self._predict_type_hints if _is_context_in_predict_function_signature(func=self.predict): ...
Internal method to get type hints from the predict function signature.
predict_type_hints
python
mlflow/mlflow
mlflow/pyfunc/model.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/model.py
Apache-2.0
def predict(self, context, model_input, params: Optional[dict[str, Any]] = None): """ Evaluates a pyfunc-compatible input and produces a pyfunc-compatible output. For more information about the pyfunc input/output API, see the :ref:`pyfunc-inference-api`. Args: context: A :c...
Evaluates a pyfunc-compatible input and produces a pyfunc-compatible output. For more information about the pyfunc input/output API, see the :ref:`pyfunc-inference-api`. Args: context: A :class:`~PythonModelContext` instance containing artifacts that the model ...
predict
python
mlflow/mlflow
mlflow/pyfunc/model.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/model.py
Apache-2.0
def predict( self, model_input, params: Optional[dict[str, Any]] = None, ): """ Args: model_input: A pyfunc-compatible input for the model to evaluate. params: Additional parameters to pass to the model for inference. Returns: Mode...
Args: model_input: A pyfunc-compatible input for the model to evaluate. params: Additional parameters to pass to the model for inference. Returns: Model predictions.
predict
python
mlflow/mlflow
mlflow/pyfunc/model.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/model.py
Apache-2.0
def __init__(self, artifacts, model_config): """ Args: artifacts: A dictionary of ``<name, artifact_path>`` entries, where ``artifact_path`` is an absolute filesystem path to a given artifact. model_config: The model configuration to make available to the model at...
Args: artifacts: A dictionary of ``<name, artifact_path>`` entries, where ``artifact_path`` is an absolute filesystem path to a given artifact. model_config: The model configuration to make available to the model at loading time.
__init__
python
mlflow/mlflow
mlflow/pyfunc/model.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/model.py
Apache-2.0
def predict( self, context, messages: list[ChatMessage], params: ChatParams ) -> ChatCompletionResponse: """ Evaluates a chat input and produces a chat output. Args: context: A :class:`~PythonModelContext` instance containing artifacts that the model can ...
Evaluates a chat input and produces a chat output. Args: context: A :class:`~PythonModelContext` instance containing artifacts that the model can use to perform inference. messages (List[:py:class:`ChatMessage <mlflow.types.llm.ChatMessage>`]): A...
predict
python
mlflow/mlflow
mlflow/pyfunc/model.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/model.py
Apache-2.0
def predict_stream( self, context, messages: list[ChatMessage], params: ChatParams ) -> Generator[ChatCompletionChunk, None, None]: """ Evaluates a chat input and produces a chat output. Override this function to implement a real stream prediction. Args: context:...
Evaluates a chat input and produces a chat output. Override this function to implement a real stream prediction. Args: context: A :class:`~PythonModelContext` instance containing artifacts that the model can use to perform inference. messages (List[:py:c...
predict_stream
python
mlflow/mlflow
mlflow/pyfunc/model.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/model.py
Apache-2.0
def predict( self, messages: list[ChatAgentMessage], context: Optional[ChatContext] = None, custom_inputs: Optional[dict[str, Any]] = None, ) -> ChatAgentResponse: """ Given a ChatAgent input, returns a ChatAgent output. In addition to calling ``predict`` with...
Given a ChatAgent input, returns a ChatAgent output. In addition to calling ``predict`` with an input matching the type hints, you can also pass a single input dict that matches the :py:class:`ChatAgentRequest <mlflow.types.agent.ChatAgentRequest>` schema for ease of testing. ....
predict
python
mlflow/mlflow
mlflow/pyfunc/model.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/model.py
Apache-2.0
def predict_stream( self, messages: list[ChatAgentMessage], context: Optional[ChatContext] = None, custom_inputs: Optional[dict[str, Any]] = None, ) -> Generator[ChatAgentChunk, None, None]: """ Given a ChatAgent input, returns a generator containing streaming ChatAge...
Given a ChatAgent input, returns a generator containing streaming ChatAgent output chunks. In addition to calling ``predict_stream`` with an input matching the type hints, you can also pass a single input dict that matches the :py:class:`ChatAgentRequest <mlflow.types.agent.ChatAgentReq...
predict_stream
python
mlflow/mlflow
mlflow/pyfunc/model.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/model.py
Apache-2.0
def predict(self, request: ResponsesAgentRequest) -> ResponsesAgentResponse: """ Given a ResponsesAgentRequest, returns a ResponsesAgentResponse. You can see example implementations at https://www.mlflow.org/docs/latest/llms/responses-agent-intro#simple-chat-example and ...
Given a ResponsesAgentRequest, returns a ResponsesAgentResponse. You can see example implementations at https://www.mlflow.org/docs/latest/llms/responses-agent-intro#simple-chat-example and https://www.mlflow.org/docs/latest/llms/responses-agent-intro#tool-calling-examp...
predict
python
mlflow/mlflow
mlflow/pyfunc/model.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/model.py
Apache-2.0
def predict_stream( self, request: ResponsesAgentRequest ) -> Generator[ResponsesAgentStreamEvent, None, None]: """ Given a ResponsesAgentRequest, returns a generator of ResponsesAgentStreamEvent objects. See more details at https://www.mlflow.org/doc...
Given a ResponsesAgentRequest, returns a generator of ResponsesAgentStreamEvent objects. See more details at https://www.mlflow.org/docs/latest/llms/responses-agent-intro#streaming-agent-output. You can see example implementations at https://www.mlflow.org/...
predict_stream
python
mlflow/mlflow
mlflow/pyfunc/model.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/model.py
Apache-2.0
def create_text_delta(self, delta: str, item_id: str) -> dict[str, Any]: """Helper method to create a dictionary conforming to the text delta schema for streaming. Read more at https://www.mlflow.org/docs/latest/llms/responses-agent-intro/#streaming-agent-output. """ ...
Helper method to create a dictionary conforming to the text delta schema for streaming. Read more at https://www.mlflow.org/docs/latest/llms/responses-agent-intro/#streaming-agent-output.
create_text_delta
python
mlflow/mlflow
mlflow/pyfunc/model.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/model.py
Apache-2.0
def create_text_output_item(self, text: str, id: str) -> dict[str, Any]: """Helper method to create a dictionary conforming to the text output item schema. Read more at https://www.mlflow.org/docs/latest/llms/responses-agent-intro/#creating-agent-output. Args: text ...
Helper method to create a dictionary conforming to the text output item schema. Read more at https://www.mlflow.org/docs/latest/llms/responses-agent-intro/#creating-agent-output. Args: text (str): The text to be outputted. id (str): The id of the output item. ...
create_text_output_item
python
mlflow/mlflow
mlflow/pyfunc/model.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/model.py
Apache-2.0
def create_function_call_item( self, id: str, call_id: str, name: str, arguments: str ) -> dict[str, Any]: """Helper method to create a dictionary conforming to the function call item schema. Read more at https://www.mlflow.org/docs/latest/llms/responses-agent-intro/#creatin...
Helper method to create a dictionary conforming to the function call item schema. Read more at https://www.mlflow.org/docs/latest/llms/responses-agent-intro/#creating-agent-output. Args: id (str): The id of the output item. call_id (str): The id of the function ...
create_function_call_item
python
mlflow/mlflow
mlflow/pyfunc/model.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/model.py
Apache-2.0
def create_function_call_output_item(self, call_id: str, output: str) -> dict[str, Any]: """Helper method to create a dictionary conforming to the function call output item schema. Read more at https://www.mlflow.org/docs/latest/llms/responses-agent-intro/#creating-agent-output. ...
Helper method to create a dictionary conforming to the function call output item schema. Read more at https://www.mlflow.org/docs/latest/llms/responses-agent-intro/#creating-agent-output. Args: call_id (str): The id of the function call. output (str)...
create_function_call_output_item
python
mlflow/mlflow
mlflow/pyfunc/model.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/model.py
Apache-2.0
def _save_model_with_class_artifacts_params( # noqa: D417 path, python_model, signature=None, artifacts=None, conda_env=None, code_paths=None, mlflow_model=None, pip_requirements=None, extra_pip_requirements=None, model_config=None, streamable=None, model_code_path=None,...
Args: path: The path to which to save the Python model. python_model: An instance of a subclass of :class:`~PythonModel`. ``python_model`` defines how the model loads artifacts and how it performs inference. artifacts: A dictionary containing ``<name, artifact_uri>`` entries. Re...
_save_model_with_class_artifacts_params
python
mlflow/mlflow
mlflow/pyfunc/model.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/model.py
Apache-2.0
def __init__(self, python_model: PythonModel, context, signature): """ Args: python_model: An instance of a subclass of :class:`~PythonModel`. context: A :class:`~PythonModelContext` instance containing artifacts that ``python_model`` may use when performing ...
Args: python_model: An instance of a subclass of :class:`~PythonModel`. context: A :class:`~PythonModelContext` instance containing artifacts that ``python_model`` may use when performing inference. signature: :class:`~ModelSignature` instance describing...
__init__
python
mlflow/mlflow
mlflow/pyfunc/model.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/model.py
Apache-2.0
def predict(self, model_input, params: Optional[dict[str, Any]] = None): """ Args: model_input: Model input data as one of dict, str, bool, bytes, float, int, str type. params: Additional parameters to pass to the model for inference. Returns: Model predictio...
Args: model_input: Model input data as one of dict, str, bool, bytes, float, int, str type. params: Additional parameters to pass to the model for inference. Returns: Model predictions as an iterator of chunks. The chunks in the iterator must be type of ...
predict
python
mlflow/mlflow
mlflow/pyfunc/model.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/model.py
Apache-2.0
def predict_stream(self, model_input, params: Optional[dict[str, Any]] = None): """ Args: model_input: LLM Model single input. params: Additional parameters to pass to the model for inference. Returns: Streaming predictions. """ parameters = i...
Args: model_input: LLM Model single input. params: Additional parameters to pass to the model for inference. Returns: Streaming predictions.
predict_stream
python
mlflow/mlflow
mlflow/pyfunc/model.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/model.py
Apache-2.0
def predict( self, context, model_input: Union[pd.DataFrame, dict[str, Any], list[dict[str, Any]]] ): """ Run prediction on the input data. Args: context: A :class:`~PythonModelContext` instance containing artifacts that the model can use to perform infer...
Run prediction on the input data. Args: context: A :class:`~PythonModelContext` instance containing artifacts that the model can use to perform inference. model_input: The input data for prediction, either of the following: - Pandas DataFrame: If...
predict
python
mlflow/mlflow
mlflow/pyfunc/model.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/model.py
Apache-2.0
def _predict_single(self, data: Union[str, dict[str, Any]]) -> dict[str, Any]: """ Send a single prediction request to the MLflow Deployments endpoint. Args: data: The single input data for prediction. If the input data is a string, we will construct the request payl...
Send a single prediction request to the MLflow Deployments endpoint. Args: data: The single input data for prediction. If the input data is a string, we will construct the request payload from it. If the input data is a dictionary, we will directly use it as...
_predict_single
python
mlflow/mlflow
mlflow/pyfunc/model.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/model.py
Apache-2.0
def get_or_load(archive_path): """Given a path returned by add_local_model(), this method will return a tuple of (loaded_model, local_model_path). If this Python process ever loaded the model before, we will reuse that copy. """ if archive_path in SparkModelCache._models: ...
Given a path returned by add_local_model(), this method will return a tuple of (loaded_model, local_model_path). If this Python process ever loaded the model before, we will reuse that copy.
get_or_load
python
mlflow/mlflow
mlflow/pyfunc/spark_model_cache.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/spark_model_cache.py
Apache-2.0
def add_to_model( model, loader_module, data=None, code=None, conda_env=None, python_env=None, model_config=None, model_code_path=None, **kwargs, ): """ Add a ``pyfunc`` spec to the model configuration. Defines ``pyfunc`` configuration schema. Caller can use this to crea...
Add a ``pyfunc`` spec to the model configuration. Defines ``pyfunc`` configuration schema. Caller can use this to create a valid ``pyfunc`` model flavor out of an existing directory structure. For example, other model flavors can use this to specify how to use their output as a ``pyfunc``. NOTE: ...
add_to_model
python
mlflow/mlflow
mlflow/pyfunc/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/__init__.py
Apache-2.0
def _validate_prediction_input(data: PyFuncInput, params, input_schema, params_schema, flavor=None): """ Internal helper function to transform and validate input data and params for prediction. Any additional transformation logics related to input data and params should be added here. """ if input_s...
Internal helper function to transform and validate input data and params for prediction. Any additional transformation logics related to input data and params should be added here.
_validate_prediction_input
python
mlflow/mlflow
mlflow/pyfunc/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/__init__.py
Apache-2.0
def _predict(self, data: PyFuncInput, params: Optional[dict[str, Any]] = None) -> PyFuncOutput: """ Generates model predictions. If the model contains signature, enforce the input schema first before calling the model implementation with the sanitized input. If the pyfunc model does not...
Generates model predictions. If the model contains signature, enforce the input schema first before calling the model implementation with the sanitized input. If the pyfunc model does not include model schema, the input is passed to the model implementation as is. See `Model Signature ...
_predict
python
mlflow/mlflow
mlflow/pyfunc/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/__init__.py
Apache-2.0
def _predict_stream( self, data: PyFuncLLMSingleInput, params: Optional[dict[str, Any]] = None ) -> Iterator[PyFuncLLMOutputChunk]: """ Generates streaming model predictions. Only LLM supports this method. If the model contains signature, enforce the input schema first before callin...
Generates streaming model predictions. Only LLM supports this method. If the model contains signature, enforce the input schema first before calling the model implementation with the sanitized input. If the pyfunc model does not include model schema, the input is passed to the model im...
_predict_stream
python
mlflow/mlflow
mlflow/pyfunc/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/__init__.py
Apache-2.0
def unwrap_python_model(self): """ Unwrap the underlying Python model object. This method is useful for accessing custom model functions, while still being able to leverage the MLflow designed workflow through the `predict()` method. Returns: The underlying wrapped ...
Unwrap the underlying Python model object. This method is useful for accessing custom model functions, while still being able to leverage the MLflow designed workflow through the `predict()` method. Returns: The underlying wrapped model object .. code-block:: pyth...
unwrap_python_model
python
mlflow/mlflow
mlflow/pyfunc/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/__init__.py
Apache-2.0
def get_raw_model(self): """ Get the underlying raw model if the model wrapper implemented `get_raw_model` function. """ if hasattr(self._model_impl, "get_raw_model"): return self._model_impl.get_raw_model() raise NotImplementedError("`get_raw_model` is not implemente...
Get the underlying raw model if the model wrapper implemented `get_raw_model` function.
get_raw_model
python
mlflow/mlflow
mlflow/pyfunc/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/__init__.py
Apache-2.0
def _load_model_or_server( model_uri: str, env_manager: str, model_config: Optional[dict[str, Any]] = None ): """ Load a model with env restoration. If a non-local ``env_manager`` is specified, prepare an independent Python environment with the training time dependencies of the specified model insta...
Load a model with env restoration. If a non-local ``env_manager`` is specified, prepare an independent Python environment with the training time dependencies of the specified model installed and start a MLflow Model Scoring Server process with that model in that environment. Return a _ServedPyFuncModel...
_load_model_or_server
python
mlflow/mlflow
mlflow/pyfunc/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/__init__.py
Apache-2.0
def get_model_dependencies(model_uri, format="pip"): """ Downloads the model dependencies and returns the path to requirements.txt or conda.yaml file. .. warning:: This API downloads all the model artifacts to the local filesystem. This may take a long time for large models. To avoid this o...
Downloads the model dependencies and returns the path to requirements.txt or conda.yaml file. .. warning:: This API downloads all the model artifacts to the local filesystem. This may take a long time for large models. To avoid this overhead, use ``mlflow.artifacts.download_artifacts("...
get_model_dependencies
python
mlflow/mlflow
mlflow/pyfunc/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/__init__.py
Apache-2.0
def _warn_potentially_incompatible_py_version_if_necessary(model_py_version=None): """ Compares the version of Python that was used to save a given model with the version of Python that is currently running. If a major or minor version difference is detected, logs an appropriate warning. """ if ...
Compares the version of Python that was used to save a given model with the version of Python that is currently running. If a major or minor version difference is detected, logs an appropriate warning.
_warn_potentially_incompatible_py_version_if_necessary
python
mlflow/mlflow
mlflow/pyfunc/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/__init__.py
Apache-2.0
def _convert_array_values(values, result_type): """ Convert list or numpy array values to spark dataframe column values. """ from pyspark.sql.types import ArrayType, StructType if not isinstance(result_type, ArrayType): raise MlflowException.invalid_parameter_value( f"result_typ...
Convert list or numpy array values to spark dataframe column values.
_convert_array_values
python
mlflow/mlflow
mlflow/pyfunc/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/__init__.py
Apache-2.0
def _convert_struct_values( result: Union[pandas.DataFrame, dict[str, Any]], result_type, ): """ Convert spark StructType values to spark dataframe column values. """ from pyspark.sql.types import ArrayType, MapType, StructType if not isinstance(result_type, StructType): raise Mlfl...
Convert spark StructType values to spark dataframe column values.
_convert_struct_values
python
mlflow/mlflow
mlflow/pyfunc/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/__init__.py
Apache-2.0
def _convert_value_based_on_spark_type(value, spark_type): """ Convert value to python types based on the given spark type. """ from pyspark.sql.types import ArrayType, MapType, StructType spark_primitive_type_to_python_type = _get_spark_primitive_type_to_python_type() if type(spark_type) in ...
Convert value to python types based on the given spark type.
_convert_value_based_on_spark_type
python
mlflow/mlflow
mlflow/pyfunc/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/__init__.py
Apache-2.0
def _gen_prebuilt_env_archive_name(spark, local_model_path): """ Generate prebuilt env archive file name. The format is: 'mlflow-{sha of python env config and dependencies}-{runtime version}-{platform machine}' Note: The runtime version and platform machine information are included in the archi...
Generate prebuilt env archive file name. The format is: 'mlflow-{sha of python env config and dependencies}-{runtime version}-{platform machine}' Note: The runtime version and platform machine information are included in the archive name because the prebuilt env might not be compatible across diff...
_gen_prebuilt_env_archive_name
python
mlflow/mlflow
mlflow/pyfunc/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/__init__.py
Apache-2.0
def build_model_env(model_uri, save_path): """ Prebuild model python environment and generate an archive file saved to provided `save_path`. Typical usages: - Pre-build a model's environment in Databricks Runtime and then download the prebuilt python environment archive file. This pre-built...
Prebuild model python environment and generate an archive file saved to provided `save_path`. Typical usages: - Pre-build a model's environment in Databricks Runtime and then download the prebuilt python environment archive file. This pre-built environment archive can then be used in `m...
build_model_env
python
mlflow/mlflow
mlflow/pyfunc/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/__init__.py
Apache-2.0
def _save_model_with_loader_module_and_data_path( # noqa: D417 path, loader_module, data_path=None, code_paths=None, conda_env=None, mlflow_model=None, pip_requirements=None, extra_pip_requirements=None, model_config=None, streamable=None, infer_code_paths=False, ): """ ...
Export model as a generic Python function model. Args: path: The path to which to save the Python model. loader_module: The name of the Python module that is used to load the model from ``data_path``. This module must define a method with the prototype ``_load_pyfunc(da...
_save_model_with_loader_module_and_data_path
python
mlflow/mlflow
mlflow/pyfunc/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/__init__.py
Apache-2.0
def _save_model_chat_agent_helper(python_model, mlflow_model, signature, input_example): """Helper method for save_model for ChatAgent models Returns: a dict input_example """ if signature is not None: raise MlflowException( "ChatAgent subclasses have a standard signature that is se...
Helper method for save_model for ChatAgent models Returns: a dict input_example
_save_model_chat_agent_helper
python
mlflow/mlflow
mlflow/pyfunc/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/__init__.py
Apache-2.0
def _save_model_responses_agent_helper(python_model, mlflow_model, signature, input_example): """Helper method for save_model for ResponsesAgent models Returns: a dictionary input example """ from mlflow.types.responses import ( RESPONSES_AGENT_INPUT_EXAMPLE, RESPONSES_AGENT_INPUT_SCHEM...
Helper method for save_model for ResponsesAgent models Returns: a dictionary input example
_save_model_responses_agent_helper
python
mlflow/mlflow
mlflow/pyfunc/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/__init__.py
Apache-2.0
def predict(self, model_input: dict[str, Any], params=None) -> dict[str, Any]: """ Args: model_input: A dict with the :py:class:`ChatAgentRequest <mlflow.types.agent.ChatAgentRequest>` schema. params: Unused in this function, but required in the signature because ...
Args: model_input: A dict with the :py:class:`ChatAgentRequest <mlflow.types.agent.ChatAgentRequest>` schema. params: Unused in this function, but required in the signature because `load_model_and_predict` in `utils/_capture_modules.py` expects a params f...
predict
python
mlflow/mlflow
mlflow/pyfunc/loaders/chat_agent.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/loaders/chat_agent.py
Apache-2.0
def predict_stream( self, model_input: dict[str, Any], params=None ) -> Generator[dict[str, Any], None, None]: """ Args: model_input: A dict with the :py:class:`ChatAgentRequest <mlflow.types.agent.ChatAgentRequest>` schema. params: Unused in this func...
Args: model_input: A dict with the :py:class:`ChatAgentRequest <mlflow.types.agent.ChatAgentRequest>` schema. params: Unused in this function, but required in the signature because `load_model_and_predict` in `utils/_capture_modules.py` expects a params f...
predict_stream
python
mlflow/mlflow
mlflow/pyfunc/loaders/chat_agent.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/loaders/chat_agent.py
Apache-2.0
def __init__(self, chat_model, context, signature): """ Args: chat_model: An instance of a subclass of :class:`~ChatModel`. context: A :class:`~PythonModelContext` instance containing artifacts that ``chat_model`` may use when performing inference. ...
Args: chat_model: An instance of a subclass of :class:`~ChatModel`. context: A :class:`~PythonModelContext` instance containing artifacts that ``chat_model`` may use when performing inference. signature: :class:`~ModelSignature` instance describing mo...
__init__
python
mlflow/mlflow
mlflow/pyfunc/loaders/chat_model.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/loaders/chat_model.py
Apache-2.0
def predict( self, model_input: dict[str, Any], params: Optional[dict[str, Any]] = None ) -> dict[str, Any]: """ Args: model_input: Model input data in the form of a chat request. params: Additional parameters to pass to the model for inference. ...
Args: model_input: Model input data in the form of a chat request. params: Additional parameters to pass to the model for inference. Unused in this implementation, as the params are handled via ``self._convert_input()``. Returns: ...
predict
python
mlflow/mlflow
mlflow/pyfunc/loaders/chat_model.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/loaders/chat_model.py
Apache-2.0
def predict_stream( self, model_input: dict[str, Any], params: Optional[dict[str, Any]] = None ) -> Generator[dict[str, Any], None, None]: """ Args: model_input: Model input data in the form of a chat request. params: Additional parameters to pass to the model for inf...
Args: model_input: Model input data in the form of a chat request. params: Additional parameters to pass to the model for inference. Unused in this implementation, as the params are handled via ``self._convert_input()``. Returns: ...
predict_stream
python
mlflow/mlflow
mlflow/pyfunc/loaders/chat_model.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/loaders/chat_model.py
Apache-2.0
def predict(self, model_input: dict[str, Any], params=None) -> dict[str, Any]: """ Args: model_input: A dict with the :py:class:`ResponsesRequest <mlflow.types.responses.ResponsesRequest>` schema. params: Unused in this function, but required in the signature beca...
Args: model_input: A dict with the :py:class:`ResponsesRequest <mlflow.types.responses.ResponsesRequest>` schema. params: Unused in this function, but required in the signature because `load_model_and_predict` in `utils/_capture_modules.py` expects a para...
predict
python
mlflow/mlflow
mlflow/pyfunc/loaders/responses_agent.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/loaders/responses_agent.py
Apache-2.0
def predict_stream( self, model_input: dict[str, Any], params=None ) -> Generator[dict[str, Any], None, None]: """ Args: model_input: A dict with the :py:class:`ResponsesRequest <mlflow.types.responses.ResponsesRequest>` schema. params: Unused in this ...
Args: model_input: A dict with the :py:class:`ResponsesRequest <mlflow.types.responses.ResponsesRequest>` schema. params: Unused in this function, but required in the signature because `load_model_and_predict` in `utils/_capture_modules.py` expects a para...
predict_stream
python
mlflow/mlflow
mlflow/pyfunc/loaders/responses_agent.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/loaders/responses_agent.py
Apache-2.0
def wait_server_ready(self, timeout=30, scoring_server_proc=None): """ Wait until the scoring server is ready to accept requests. """
Wait until the scoring server is ready to accept requests.
wait_server_ready
python
mlflow/mlflow
mlflow/pyfunc/scoring_server/client.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/scoring_server/client.py
Apache-2.0
def invoke(self, data, params: Optional[dict[str, Any]] = None): """ Invoke inference on input data. The input data must be pandas dataframe or numpy array or a dict of numpy arrays. Args: data: Model input data. params: Additional parameters to pass to the model...
Invoke inference on input data. The input data must be pandas dataframe or numpy array or a dict of numpy arrays. Args: data: Model input data. params: Additional parameters to pass to the model for inference. Returns: Prediction result.
invoke
python
mlflow/mlflow
mlflow/pyfunc/scoring_server/client.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/scoring_server/client.py
Apache-2.0
def invoke(self, data, params: Optional[dict[str, Any]] = None): """ Args: data: Model input data. params: Additional parameters to pass to the model for inference. Returns: :py:class:`PredictionsResponse <mlflow.deployments.PredictionsResponse>` result. ...
Args: data: Model input data. params: Additional parameters to pass to the model for inference. Returns: :py:class:`PredictionsResponse <mlflow.deployments.PredictionsResponse>` result.
invoke
python
mlflow/mlflow
mlflow/pyfunc/scoring_server/client.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/scoring_server/client.py
Apache-2.0
def invoke(self, data, params: Optional[dict[str, Any]] = None): """ Invoke inference on input data. The input data must be pandas dataframe or numpy array or a dict of numpy arrays. Args: data: Model input data. params: Additional parameters to pass to the model...
Invoke inference on input data. The input data must be pandas dataframe or numpy array or a dict of numpy arrays. Args: data: Model input data. params: Additional parameters to pass to the model for inference. Returns: :py:class:`PredictionsResponse...
invoke
python
mlflow/mlflow
mlflow/pyfunc/scoring_server/client.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/scoring_server/client.py
Apache-2.0
def infer_and_parse_json_input(json_input, schema: Schema = None): """ Args: json_input: A JSON-formatted string representation of TF serving input or a Pandas DataFrame, or a stream containing such a string representation. schema: Optional schema specification to be used dur...
Args: json_input: A JSON-formatted string representation of TF serving input or a Pandas DataFrame, or a stream containing such a string representation. schema: Optional schema specification to be used during parsing.
infer_and_parse_json_input
python
mlflow/mlflow
mlflow/pyfunc/scoring_server/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/scoring_server/__init__.py
Apache-2.0
def _decode_json_input(json_input): """ Args: json_input: A JSON-formatted string representation of TF serving input or a Pandas DataFrame, or a stream containing such a string representation. Returns: A dictionary representation of the JSON input. """ if isinsta...
Args: json_input: A JSON-formatted string representation of TF serving input or a Pandas DataFrame, or a stream containing such a string representation. Returns: A dictionary representation of the JSON input.
_decode_json_input
python
mlflow/mlflow
mlflow/pyfunc/scoring_server/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/scoring_server/__init__.py
Apache-2.0
def infer_and_parse_data(data, schema: Schema = None): """ Args: data: A dictionary representation of TF serving input or a Pandas DataFrame, or a stream containing such a string representation. schema: Optional schema specification to be used during parsing. """ format_keys...
Args: data: A dictionary representation of TF serving input or a Pandas DataFrame, or a stream containing such a string representation. schema: Optional schema specification to be used during parsing.
infer_and_parse_data
python
mlflow/mlflow
mlflow/pyfunc/scoring_server/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/scoring_server/__init__.py
Apache-2.0
def parse_csv_input(csv_input, schema: Schema = None): """ Args: csv_input: A CSV-formatted string representation of a Pandas DataFrame, or a stream containing such a string representation. schema: Optional schema specification to be used during parsing. """ import pan...
Args: csv_input: A CSV-formatted string representation of a Pandas DataFrame, or a stream containing such a string representation. schema: Optional schema specification to be used during parsing.
parse_csv_input
python
mlflow/mlflow
mlflow/pyfunc/scoring_server/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/scoring_server/__init__.py
Apache-2.0
def _handle_serving_error(error_message, error_code, include_traceback=True): """ Logs information about an exception thrown by model inference code that is currently being handled and reraises it with the specified error message. The exception stack trace is also included in the reraised error message....
Logs information about an exception thrown by model inference code that is currently being handled and reraises it with the specified error message. The exception stack trace is also included in the reraised error message. Args: error_message: A message for the reraised exception. erro...
_handle_serving_error
python
mlflow/mlflow
mlflow/pyfunc/scoring_server/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/scoring_server/__init__.py
Apache-2.0
def init(model: PyFuncModel): """ Initialize the server. Loads pyfunc model from the path. """ from fastapi import FastAPI, Request from fastapi.responses import Response app = FastAPI() input_schema = model.metadata.get_input_schema() # set the environment variable to indicate that we ...
Initialize the server. Loads pyfunc model from the path.
init
python
mlflow/mlflow
mlflow/pyfunc/scoring_server/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/scoring_server/__init__.py
Apache-2.0
async def ping(request: Request): """ Determine if the container is working and healthy. We declare it healthy if we can load the model successfully. """ health = model is not None status = 200 if health else 404 return Response(content="\n", status_code=status, m...
Determine if the container is working and healthy. We declare it healthy if we can load the model successfully.
ping
python
mlflow/mlflow
mlflow/pyfunc/scoring_server/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/scoring_server/__init__.py
Apache-2.0
async def transformation(request: Request): """ Do an inference on a single batch of data. In this sample server, we take data as CSV or json, convert it to a Pandas DataFrame or Numpy, generate predictions and convert them back to json. """ data = await request.body() ...
Do an inference on a single batch of data. In this sample server, we take data as CSV or json, convert it to a Pandas DataFrame or Numpy, generate predictions and convert them back to json.
transformation
python
mlflow/mlflow
mlflow/pyfunc/scoring_server/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/scoring_server/__init__.py
Apache-2.0
def pyfunc(func): """ A decorator that forces data validation against type hint of the input data in the wrapped method. It is no-op if the type hint is not supported by MLflow. .. note:: The function that applies this decorator must be a valid `predict` function of `mlflow.pyfunc.Pytho...
A decorator that forces data validation against type hint of the input data in the wrapped method. It is no-op if the type hint is not supported by MLflow. .. note:: The function that applies this decorator must be a valid `predict` function of `mlflow.pyfunc.PythonModel`, or a callable th...
pyfunc
python
mlflow/mlflow
mlflow/pyfunc/utils/data_validation.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/utils/data_validation.py
Apache-2.0
def wrap_non_list_predict_pydantic(func, input_pydantic_model, validation_error_msg, unpack=False): """ Used by MLflow defined subclasses of PythonModel that have non-list a pydantic model as input. Takes in a dict input, validates it against `input_pydantic_model`, and then creates the pydantic model. ...
Used by MLflow defined subclasses of PythonModel that have non-list a pydantic model as input. Takes in a dict input, validates it against `input_pydantic_model`, and then creates the pydantic model. If `unpack` is True, the validated dict is parsed into the function arguments. Otherwise, the whol...
wrap_non_list_predict_pydantic
python
mlflow/mlflow
mlflow/pyfunc/utils/data_validation.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/utils/data_validation.py
Apache-2.0
def _get_func_info_if_type_hint_supported(func) -> Optional[FuncInfo]: """ Internal method to check if the predict function has type hints and if they are supported by MLflow. For PythonModel, the signature must be one of below: - predict(self, context, model_input, params=None) - predic...
Internal method to check if the predict function has type hints and if they are supported by MLflow. For PythonModel, the signature must be one of below: - predict(self, context, model_input, params=None) - predict(self, model_input, params=None) For callables, the function must contain...
_get_func_info_if_type_hint_supported
python
mlflow/mlflow
mlflow/pyfunc/utils/data_validation.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pyfunc/utils/data_validation.py
Apache-2.0