repo
stringclasses
454 values
file_path
stringlengths
5
201
extension
stringclasses
1 value
content
stringlengths
8
509k
num_lines
int64
3
16.9k
size_bytes
int64
8
511k
mlflow
mlflow/utils/huggingface_utils.py
.py
import functools import logging import os import time from mlflow.environment_variables import _MLFLOW_TESTING from mlflow.exceptions import MlflowException from mlflow.protos.databricks_pb2 import RESOURCE_DOES_NOT_EXIST _logger = logging.getLogger(__name__) # NB: The maxsize=1 is added for encouraging the cache r...
83
2,966
mlflow
mlflow/utils/string_utils.py
.py
import re import shlex from datetime import datetime from typing import Any from mlflow.utils.os import is_windows def strip_prefix(original: str, prefix: str) -> str: if original.startswith(prefix): return original[len(prefix) :] return original def strip_suffix(original: str, suffix: str) -> str:...
191
6,079
mlflow
mlflow/utils/thread_utils.py
.py
import contextvars import os import threading from collections.abc import Callable, Iterable from concurrent.futures import ThreadPoolExecutor from typing import Any, TypeVar T = TypeVar("T") R = TypeVar("R") class ThreadLocalVariable: """ Class for creating a thread local variable. Args: defaul...
86
2,932
mlflow
mlflow/utils/jsonpath_utils.py
.py
""" JSONPath utilities for navigating and manipulating nested JSON structures. This module provides a simplified JSONPath-like implementation without adding external dependencies to MLflow. Instead of using a full JSONPath library, we implement a lightweight subset focused on trace data navigation using dot notation w...
333
12,173
mlflow
mlflow/utils/environment.py
.py
import hashlib import importlib.metadata import logging import os import pathlib import re import shutil import subprocess import sys import tempfile from copy import deepcopy import yaml from packaging.requirements import InvalidRequirement, Requirement from packaging.specifiers import SpecifierSet from packaging.ver...
1,128
43,175
mlflow
mlflow/utils/server_cli_utils.py
.py
""" Utilities for MLflow cli server config validation and resolving. NOTE: these functions are intended to be used as utilities for the cli click-based interface. Do not use for any other purpose as the potential Exceptions being raised will be misleading for users. """ import click from mlflow.environment_variables ...
95
3,591
mlflow
mlflow/utils/rest_utils.py
.py
import base64 import contextlib import json import logging import random import time import warnings from contextvars import ContextVar from functools import lru_cache from typing import Any, Callable import requests from mlflow.environment_variables import ( _MLFLOW_DATABRICKS_TRAFFIC_ID, _MLFLOW_HTTP_REQUES...
809
31,874
mlflow
mlflow/utils/workspace_utils.py
.py
from __future__ import annotations from mlflow.environment_variables import MLFLOW_WORKSPACE, MLFLOW_WORKSPACE_STORE_URI _workspace_store_uri: str | None = None DEFAULT_WORKSPACE_NAME = "default" WORKSPACES_DIR_NAME = "workspaces" WORKSPACE_HEADER_NAME = "X-MLFLOW-WORKSPACE" def _normalize_workspace(workspace: str...
119
3,459
mlflow
mlflow/utils/databricks_tracing_utils.py
.py
import logging from google.protobuf.duration_pb2 import Duration from google.protobuf.timestamp_pb2 import Timestamp from mlflow.entities import Assessment, Span, Trace, TraceData, TraceInfo from mlflow.entities.trace_info_v2 import _truncate_request_metadata, _truncate_tags from mlflow.entities.trace_location import...
292
11,200
mlflow
mlflow/utils/mime_type_utils.py
.py
import os import pathlib from mimetypes import guess_type from mlflow.version import IS_TRACING_SDK_ONLY # TODO: Create a module to define constants to avoid circular imports # and move MLMODEL_FILE_NAME and MLPROJECT_FILE_NAME in the module. def get_text_extensions(): exts = [ "txt", "log", ...
59
1,409
mlflow
mlflow/utils/__init__.py
.py
import importlib.metadata import inspect import logging import socket import subprocess import uuid from contextlib import closing from itertools import islice from sys import version_info from packaging.version import InvalidVersion, Version PYTHON_VERSION = f"{version_info.major}.{version_info.minor}.{version_info....
334
10,356
mlflow
mlflow/utils/promptlab_utils.py
.py
import json import os import tempfile import time from datetime import datetime, timezone from mlflow.entities.param import Param from mlflow.entities.run_status import RunStatus from mlflow.entities.run_tag import RunTag from mlflow.utils.file_utils import make_containing_dirs, write_to from mlflow.utils.mlflow_tags ...
147
5,598
mlflow
mlflow/utils/git_utils.py
.py
import logging import os from urllib.parse import urlsplit, urlunsplit _logger = logging.getLogger(__name__) def _strip_credentials_from_url(url: str) -> str: """ Strip any embedded userinfo (username/password) from a URL so it's safe to record as a tag. HTTP(S) and similar remotes can carry credentials...
98
3,430
mlflow
mlflow/utils/_unity_catalog_utils.py
.py
import logging from typing import Callable from mlflow.entities.logged_model_parameter import LoggedModelParameter as ModelParam from mlflow.entities.metric import Metric from mlflow.entities.model_registry import ( ModelVersion, ModelVersionDeploymentJobState, ModelVersionTag, RegisteredModel, Reg...
497
19,713
mlflow
mlflow/utils/mlflow_tags.py
.py
""" File containing all of the run tags in the mlflow. namespace. See the System Tags section in the MLflow Tracking documentation for information on the meaning of these tags. """ MLFLOW_EXPERIMENT_SOURCE_ID = "mlflow.experiment.sourceId" MLFLOW_EXPERIMENT_SOURCE_TYPE = "mlflow.experiment.sourceType" MLFLOW_EXPERIME...
159
7,118
mlflow
mlflow/utils/logging_utils.py
.py
import contextlib import logging import re import sys from mlflow.environment_variables import MLFLOW_LOGGING_LEVEL from mlflow.utils.thread_utils import ThreadLocalVariable def get_mlflow_log_level() -> str: """Returns the log level from MLFLOW_LOGGING_LEVEL env var, defaulting to INFO.""" return (MLFLOW_LO...
257
8,538
mlflow
mlflow/utils/databricks_utils.py
.py
import functools import getpass import json import logging import os import platform import re import subprocess import time from dataclasses import dataclass from typing import TYPE_CHECKING, Any, Callable, NamedTuple, ParamSpec, TypeVar from urllib.parse import urlparse from packaging.version import Version from ml...
1,716
64,124
mlflow
mlflow/utils/search_logged_model_utils.py
.py
import ast import re from dataclasses import dataclass from enum import Enum import sqlalchemy import sqlparse from mlflow.exceptions import MlflowException from mlflow.store.tracking.dbmodels.models import SqlLoggedModel from mlflow.utils.search_utils import _join_in_comparison_tokens class EntityType(Enum): A...
127
4,245
mlflow
mlflow/utils/uv_utils.py
.py
""" Utilities for uv package manager integration. This module provides functions for detecting uv projects and exporting dependencies via ``uv export`` for automatic dependency inference during model logging. """ import logging import os import re import shutil import subprocess from pathlib import Path from typing i...
470
15,222
mlflow
mlflow/utils/gorilla.py
.py
# __ __ __ # .-----.-----.----|__| | .---.-. # | _ | _ | _| | | | _ | # |___ |_____|__| |__|__|__|___._| # |_____| # """ NOTE: The contents of this file have been inlined from the gorilla package's source code https://github.com/christophercrouzet/gorilla/blob/v0.3.0/gorilla.p...
798
24,049
mlflow
mlflow/utils/request_utils.py
.py
# DO NO IMPORT MLFLOW IN THIS FILE. # This file is imported by download_cloud_file_chunk.py. # Importing mlflow is time-consuming and we want to avoid that in artifact download subprocesses. import os import random import socket from functools import lru_cache import requests import urllib3 from packaging.version impo...
325
12,039
mlflow
mlflow/utils/env_manager.py
.py
from mlflow.exceptions import MlflowException from mlflow.protos.databricks_pb2 import INVALID_PARAMETER_VALUE LOCAL = "local" CONDA = "conda" VIRTUALENV = "virtualenv" UV = "uv" def validate(env_manager): allowed_values = [LOCAL, CONDA, VIRTUALENV, UV] if env_manager not in allowed_values: raise Mlf...
17
488
mlflow
mlflow/utils/docstring_utils.py
.py
import textwrap import warnings from typing import Any from mlflow.ml_package_versions import _ML_PACKAGE_VERSIONS from mlflow.utils.autologging_utils.versioning import ( get_min_max_version_and_pip_release, ) def _create_placeholder(key: str): return "{{ " + key + " }}" def _replace_keys_with_placeholders...
520
21,288
mlflow
mlflow/utils/file_utils.py
.py
import atexit import codecs import errno import fnmatch import gzip import importlib.util import json import logging import math import os import pathlib import posixpath import shutil import stat import subprocess import sys import tarfile import tempfile import time import urllib.parse import urllib.request from conc...
987
32,784
mlflow
mlflow/utils/databricks_sql_warehouse.py
.py
""" Helpers for making sure a Databricks SQL warehouse is running before MLflow tracing API calls that require it. """ import logging import time from datetime import timedelta from mlflow.environment_variables import ( MLFLOW_SQL_WAREHOUSE_AUTO_START, MLFLOW_SQL_WAREHOUSE_AUTO_START_TIMEOUT_SECONDS, ) from m...
85
3,115
mlflow
mlflow/utils/requirements_utils.py
.py
""" This module provides a set of utilities for interpreting and creating requirements files (e.g. pip's `requirements.txt`), which is useful for managing ML software environments. """ import importlib.metadata import json import logging import os import re import subprocess import sys import tempfile from itertools i...
709
26,984
mlflow
mlflow/utils/download_cloud_file_chunk.py
.py
""" This script should be executed in a fresh python interpreter process using `subprocess`. """ import argparse import importlib.util import json import os import sys def parse_args(): parser = argparse.ArgumentParser() parser.add_argument("--range-start", required=True, type=int) parser.add_argument("-...
44
1,241
mlflow
mlflow/utils/conda.py
.py
import hashlib import json import logging import os import yaml from mlflow.environment_variables import MLFLOW_CONDA_CREATE_ENV_CMD, MLFLOW_CONDA_HOME from mlflow.exceptions import ExecutionException from mlflow.utils import process from mlflow.utils.environment import Environment from mlflow.utils.os import is_wind...
358
13,277
mlflow
mlflow/utils/_capture_transformers_modules.py
.py
""" This script should be executed in a fresh python interpreter process using `subprocess`. """ import json import os import sys import mlflow from mlflow.exceptions import MlflowException from mlflow.protos.databricks_pb2 import INVALID_PARAMETER_VALUE from mlflow.utils._capture_modules import ( _CaptureImporte...
76
2,584
mlflow
mlflow/utils/plugins.py
.py
import importlib.metadata def _get_entry_points(group: str) -> list[importlib.metadata.EntryPoint]: return importlib.metadata.entry_points(group=group) def get_entry_points(group: str) -> list[importlib.metadata.EntryPoint]: return _get_entry_points(group)
10
269
mlflow
mlflow/utils/yaml_utils.py
.py
import codecs import os import shutil import tempfile import yaml from mlflow.utils.file_utils import ENCODING, exists, get_parent_dir try: from yaml import CSafeDumper as YamlSafeDumper from yaml import CSafeLoader as YamlSafeLoader except ImportError: from yaml import SafeDumper as YamlSafeDumper ...
122
4,339
mlflow
mlflow/utils/server_info.py
.py
from __future__ import annotations import os import threading import time from collections import OrderedDict from dataclasses import dataclass, field from typing import Any from mlflow.utils.rest_utils import MlflowHostCreds, http_request SERVER_INFO_ENDPOINT = "/api/3.0/mlflow/server-info" SERVER_INFO_STORE_TYPE ...
154
4,769
mlflow
mlflow/utils/checkpoint_utils.py
.py
import logging import os import posixpath import mlflow from mlflow.exceptions import MlflowException from mlflow.utils.autologging_utils import ( ExceptionSafeAbstractClass, ) from mlflow.utils.file_utils import TempDir from mlflow.utils.mlflow_tags import LATEST_CHECKPOINT_ARTIFACT_TAG_KEY _logger = logging.get...
207
8,591
mlflow
mlflow/utils/time.py
.py
import datetime import time def get_current_time_millis(): """ Returns the time in milliseconds since the epoch as an integer number. """ return int(time.time() * 1000) def conv_longdate_to_str(longdate, local_tz=True): date_time = datetime.datetime.fromtimestamp(longdate / 1000.0) str_long_...
54
1,260
mlflow
mlflow/utils/cli_args.py
.py
""" Definitions of click options shared by several CLI commands. """ import warnings import click from mlflow.environment_variables import MLFLOW_DISABLE_ENV_MANAGER_CONDA_WARNING from mlflow.utils import env_manager as _EnvManager MODEL_PATH = click.option( "--model-path", "-m", default=None, metav...
302
10,406
mlflow
mlflow/utils/annotations.py
.py
import inspect import re import types import warnings from functools import wraps from typing import Callable, ParamSpec, TypeVar, overload def _get_min_indent_of_docstring(docstring_str: str) -> str: """ Get the minimum indentation string of a docstring, based on the assumption that the closing triple qu...
339
11,558
mlflow
mlflow/utils/proto_json_utils.py
.py
import base64 import datetime import importlib import json import os from collections import defaultdict from copy import deepcopy from functools import partial from json import JSONEncoder from typing import Any import pydantic from google.protobuf.descriptor import FieldDescriptor from google.protobuf.duration_pb2 i...
736
28,650
mlflow
mlflow/utils/_capture_modules.py
.py
""" This script should be executed in a fresh python interpreter process using `subprocess`. """ import argparse import builtins import functools import importlib import json import os import sys import mlflow from mlflow.models.model import MLMODEL_FILE_NAME, Model from mlflow.pyfunc import MAIN from mlflow.utils._s...
260
10,270
mlflow
mlflow/utils/workspace_context.py
.py
from __future__ import annotations from contextvars import ContextVar, Token from mlflow.environment_variables import MLFLOW_WORKSPACE from mlflow.utils.workspace_utils import DEFAULT_WORKSPACE_NAME _WORKSPACE: ContextVar[str | None] = ContextVar("mlflow_active_workspace", default=None) _IS_WORKSPACE_RESOLVED: Conte...
126
4,110
mlflow
mlflow/utils/semver_utils.py
.py
from __future__ import annotations import re from dataclasses import dataclass from mlflow.exceptions import MlflowException # Keep this SemVer-specific implementation instead of ``packaging.Version``: # MLflow needs SemVer 2.0.0 precedence, while ``packaging.Version`` implements # PEP 440 and would normalize or rej...
178
6,892
mlflow
mlflow/utils/nfs_on_spark.py
.py
import os import shutil import uuid from mlflow.utils._spark_utils import _get_active_spark_session from mlflow.utils.databricks_utils import ( get_databricks_nfs_temp_dir, is_databricks_connect, is_in_databricks_runtime, is_in_databricks_serverless_runtime, ) # Set spark config "spark.mlflow.nfs.root...
63
2,698
mlflow
mlflow/utils/credentials.py
.py
import configparser import getpass import logging import os from typing import NamedTuple from mlflow.environment_variables import ( MLFLOW_TRACKING_AUTH, MLFLOW_TRACKING_AWS_SIGV4, MLFLOW_TRACKING_CLIENT_CERT_PATH, MLFLOW_TRACKING_INSECURE_TLS, MLFLOW_TRACKING_PASSWORD, MLFLOW_TRACKING_SERVER_...
241
8,692
mlflow
mlflow/utils/model_utils.py
.py
import contextlib import json import logging import os import shutil import sys from pathlib import Path from typing import Any import yaml from mlflow.exceptions import MlflowException from mlflow.models import Model from mlflow.models.model import MLMODEL_FILE_NAME from mlflow.protos.databricks_pb2 import ( INV...
536
20,851
mlflow
mlflow/utils/os.py
.py
import os def is_windows(): """ Returns true if the local system/OS name is Windows. Returns: True if the local system/OS name is Windows. """ return os.name == "nt"
13
198
mlflow
mlflow/utils/warnings_utils.py
.py
import warnings # ANSI escape code ANSI_BASE = "\033[" COLORS = { "default_bold": f"{ANSI_BASE}1m", "red": f"{ANSI_BASE}31m", "red_bold": f"{ANSI_BASE}1;31m", "yellow": f"{ANSI_BASE}33m", "yellow_bold": f"{ANSI_BASE}1;33m", "blue": f"{ANSI_BASE}34m", "blue_bold": f"{ANSI_BASE}1;34m", } RESE...
26
627
mlflow
mlflow/utils/providers.py
.py
import functools import importlib.resources import json import logging import urllib.parse import urllib.request from collections.abc import Iterator from pathlib import Path from typing import TypedDict import cachetools from typing_extensions import NotRequired from mlflow.environment_variables import MLFLOW_MODEL_...
1,077
38,760
mlflow
mlflow/utils/uri.py
.py
import os import pathlib import posixpath import re import urllib.parse import uuid from typing import Any from mlflow.exceptions import MlflowException from mlflow.protos.databricks_pb2 import INVALID_PARAMETER_VALUE from mlflow.utils.os import is_windows from mlflow.utils.validation import _validate_db_type_string ...
613
22,625
mlflow
mlflow/utils/arguments_utils.py
.py
import inspect def _get_arg_names(f): """Get the argument names of a function. Args: f: A function. Returns: A list of argument names. """ # `inspect.getargspec` or `inspect.getfullargspec` doesn't work properly for a wrapped function. # See https://hynek.me/articles/decorat...
17
412
mlflow
mlflow/utils/validation.py
.py
""" Utilities for validating user inputs such as metric names and parameter names. """ import ipaddress import json import logging import numbers import posixpath import re import socket import threading import urllib.parse from fnmatch import fnmatch from typing import Any from mlflow.entities import Dataset, Datase...
1,203
44,967
mlflow
mlflow/utils/doctor.py
.py
import os import platform import click import importlib_metadata import yaml from packaging.requirements import Requirement import mlflow from mlflow.utils.databricks_utils import get_databricks_runtime_version def doctor(mask_envs=False): """Prints out useful information for debugging issues with MLflow. ...
124
3,892
mlflow
mlflow/utils/crypto.py
.py
import json import logging import os from dataclasses import dataclass from typing import Any from mlflow.exceptions import MlflowException from mlflow.protos.databricks_pb2 import INVALID_PARAMETER_VALUE # KEK (Key Encryption Key) environment variables for envelope encryption # These are defined here to avoid import...
651
24,824
mlflow
mlflow/utils/provider_filter.py
.py
import logging import threading from cachetools import LRUCache from cachetools.func import cached from mlflow.environment_variables import MLFLOW_GATEWAY_ALLOWED_PROVIDERS _logger = logging.getLogger(__name__) # Single source of truth for provider name aliases (string-level). _PROVIDER_ALIASES: dict[str, str] = { ...
63
1,804
mlflow
mlflow/utils/data_utils.py
.py
import urllib.parse from typing import Any def parse_s3_uri(uri): """Parse an S3 URI, returning (bucket, path)""" parsed = urllib.parse.urlparse(uri) if parsed.scheme != "s3": raise Exception(f"Not an S3 URI: {uri}") path = parsed.path path = path.removeprefix("/") return parsed.netloc...
27
609
mlflow
mlflow/utils/openai_utils.py
.py
import os import time from enum import Enum from typing import NamedTuple import mlflow REQUEST_URL_CHAT = "https://api.openai.com/v1/chat/completions" REQUEST_URL_COMPLETIONS = "https://api.openai.com/v1/completions" REQUEST_URL_EMBEDDINGS = "https://api.openai.com/v1/embeddings" REQUEST_FIELDS_CHAT = { "model"...
165
5,215
mlflow
mlflow/utils/async_logging/async_logging_queue.py
.py
""" Defines an AsyncLoggingQueue that provides async fashion logging of metrics/tags/params using queue based approach. """ import atexit import enum import logging import threading from concurrent.futures import ThreadPoolExecutor from queue import Empty, Queue from typing import Callable from mlflow.entities.metric...
367
14,279
mlflow
mlflow/utils/async_logging/run_artifact.py
.py
import threading from typing import TYPE_CHECKING, Union if TYPE_CHECKING: import PIL class RunArtifact: def __init__( self, filename: str, artifact_path: str, artifact: Union["PIL.Image.Image"], completion_event: threading.Event, ) -> None: """Initializes ...
39
1,074
mlflow
mlflow/utils/async_logging/run_batch.py
.py
import threading from mlflow.entities.metric import Metric from mlflow.entities.param import Param from mlflow.entities.run_tag import RunTag class RunBatch: def __init__( self, run_id: str, params: list["Param"] | None = None, tags: list["RunTag"] | None = None, metrics: ...
58
1,802
mlflow
mlflow/utils/async_logging/run_operations.py
.py
class RunOperations: """Class that helps manage the futures of MLflow async logging.""" def __init__(self, operation_futures): self._operation_futures = operation_futures or [] def wait(self): """Blocks on completion of all futures.""" from mlflow.exceptions import MlflowException ...
50
1,944
mlflow
mlflow/utils/async_logging/async_artifacts_logging_queue.py
.py
""" Defines an AsyncArtifactsLoggingQueue that provides async fashion artifact writes using queue based approach. """ import atexit import logging import threading from concurrent.futures import ThreadPoolExecutor from queue import Empty, Queue from typing import TYPE_CHECKING, Callable, Union from mlflow.utils.async...
259
9,993
mlflow
mlflow/utils/import_hooks/__init__.py
.py
""" NOTE: The contents of this file have been inlined from the wrapt package's source code https://github.com/GrahamDumpleton/wrapt/blob/1.12.1/src/wrapt/importer.py. Some modifications, have been made in order to: - avoid duplicate registration of import hooks - inline functions from dependent wrapt submodules...
358
13,321
mlflow
mlflow/utils/autologging_utils/metrics_queue.py
.py
import concurrent.futures from threading import RLock from mlflow.entities import Metric from mlflow.tracking.client import MlflowClient _metrics_queue_lock = RLock() _metrics_queue = [] _thread_pool = concurrent.futures.ThreadPoolExecutor( max_workers=1, thread_name_prefix="MlflowMetricsQueue" ) _MAX_METRIC_QUE...
74
2,739
mlflow
mlflow/utils/autologging_utils/logging_and_warnings.py
.py
import os import warnings from pathlib import Path from threading import RLock from threading import get_ident as get_current_thread_id import mlflow from mlflow.utils import logging_utils class _WarningsController: """ Provides threadsafe utilities to modify warning behavior for MLflow autologging, includin...
329
14,328
mlflow
mlflow/utils/autologging_utils/__init__.py
.py
import contextlib import importlib import importlib.metadata import inspect import logging import threading import time from typing import Any, Callable import mlflow from mlflow.entities import Metric from mlflow.utils.validation import MAX_METRICS_PER_BATCH # Define the module-level logger for autologging utilities...
725
29,613
mlflow
mlflow/utils/autologging_utils/safety.py
.py
import abc import functools import inspect import itertools import uuid from contextlib import asynccontextmanager, contextmanager from typing import Any, Callable, NamedTuple import mlflow import mlflow.utils.autologging_utils from mlflow.entities.run_status import RunStatus from mlflow.environment_variables import _...
1,158
53,597
mlflow
mlflow/utils/autologging_utils/client.py
.py
""" Defines an MlflowAutologgingQueueingClient developer API that provides batching, queueing, and asynchronous execution capabilities for a subset of MLflow Tracking logging operations used most frequently by autologging operations. TODO(dbczumar): Migrate request batching, queueing, and async execution support from ...
437
16,877
mlflow
mlflow/utils/autologging_utils/config.py
.py
import logging from dataclasses import dataclass from typing import Any from mlflow.utils.autologging_utils import AUTOLOGGING_INTEGRATIONS _logger = logging.getLogger(__name__) @dataclass class AutoLoggingConfig: """ A dataclass to hold common autologging configuration options. """ log_input_examp...
34
1,099
mlflow
mlflow/utils/autologging_utils/versioning.py
.py
import importlib import importlib.metadata import re from typing import Literal from packaging.version import InvalidVersion, Version from mlflow.ml_package_versions import _ML_PACKAGE_VERSIONS, FLAVOR_TO_MODULE_NAME from mlflow.utils.databricks_utils import is_in_databricks_runtime def _check_version_in_range(ver,...
111
4,540
mlflow
mlflow/utils/autologging_utils/events.py
.py
import warnings from typing import Any from mlflow.utils.autologging_utils import _logger def _catch_exception(fn): """A decorator that catches exceptions thrown by the wrapped function and logs them.""" def wrapper(*args): try: fn(*args) except Exception as e: _logge...
295
13,155
mlflow
mlflow/pyspark/__init__.py
.py
from mlflow.pyspark import ml __all__ = ["ml"]
4
48
mlflow
mlflow/pyspark/optuna/study.py
.py
import datetime import logging import tempfile import traceback from collections.abc import Callable, Iterable, Sequence from dataclasses import dataclass from pathlib import Path from typing import Any import optuna import pandas as pd from optuna import exceptions, pruners, samplers, storages from optuna.study impor...
431
17,775
mlflow
mlflow/pyspark/ml/__init__.py
.py
import importlib.resources import json import logging import os import traceback import weakref from collections import OrderedDict, defaultdict from itertools import zip_longest from typing import Any, NamedTuple from urllib.parse import urlparse import numpy as np import mlflow from mlflow.data.code_dataset_source ...
1,263
55,595
mlflow
mlflow/pyspark/ml/_autolog.py
.py
import re from functools import reduce try: # For spark >= 4.0 from pyspark.errors.exceptions.base import IllegalArgumentException except ModuleNotFoundError: from pyspark.sql.utils import IllegalArgumentException from pyspark.ml.base import Transformer from pyspark.ml.functions import vector_to_array from...
97
3,068
mlflow
mlflow/gateway/uc_function_utils.py
.py
# TODO: Move this in mlflow/gateway/utils/uc_functions.py import json import re from dataclasses import dataclass from io import StringIO from typing import TYPE_CHECKING, Any, Literal if TYPE_CHECKING: from databricks.sdk import WorkspaceClient from databricks.sdk.service.catalog import FunctionInfo, Functio...
347
12,558
mlflow
mlflow/gateway/guardrails.py
.py
from __future__ import annotations import abc import asyncio import json from contextlib import nullcontext from typing import TYPE_CHECKING, Any from fastapi import HTTPException import mlflow from mlflow.entities import SpanType from mlflow.entities.assessment import Feedback from mlflow.entities.gateway_guardrail...
451
17,038
mlflow
mlflow/gateway/app.py
.py
import os from pathlib import Path from typing import Any from fastapi import FastAPI, HTTPException, Request from fastapi.openapi.docs import get_swagger_ui_html from fastapi.responses import FileResponse, RedirectResponse from pydantic import BaseModel, ConfigDict from slowapi import Limiter, _rate_limit_exceeded_ha...
487
18,533
mlflow
mlflow/gateway/tracing_utils.py
.py
import dataclasses import functools import inspect import json import logging from collections.abc import Callable from typing import Any import pydantic import mlflow from mlflow.entities import SpanStatus, SpanType from mlflow.entities.trace_location import MlflowExperimentLocation from mlflow.gateway.config import...
659
25,110
mlflow
mlflow/gateway/utils.py
.py
import base64 import functools import json import logging import posixpath import re from typing import Any, AsyncGenerator, Iterator from urllib.parse import urlparse from fastapi import HTTPException from mlflow.environment_variables import MLFLOW_GATEWAY_URI from mlflow.exceptions import MlflowException from mlflo...
449
14,745
mlflow
mlflow/gateway/exceptions.py
.py
class AIGatewayConfigException(Exception): pass class AIGatewayException(Exception): """ A custom exception class for handling exceptions raised by the AI Gateway. This will be transformed into an HTTPException before being returned to the client. """ def __init__(self, status_code: int, deta...
15
431
mlflow
mlflow/gateway/runner.py
.py
import logging import os import subprocess import sys from typing import Generator from watchfiles import watch from mlflow.environment_variables import ( MLFLOW_GATEWAY_CONFIG, MLFLOW_GATEWAY_RESOLVE_API_KEY_FROM_ENV, MLFLOW_GATEWAY_RESOLVE_API_KEY_FROM_FILE, ) from mlflow.gateway import app from mlflow....
113
3,060
mlflow
mlflow/gateway/__init__.py
.py
from mlflow.gateway.utils import get_gateway_uri, set_gateway_uri __all__ = [ "get_gateway_uri", "set_gateway_uri", ]
7
127
mlflow
mlflow/gateway/base_models.py
.py
from typing import Any from pydantic import BaseModel class RequestModel( BaseModel, # Allow extra fields for pydantic request models, e.g. to support # vendor-specific embeddings parameters extra="allow", ): """ A pydantic model representing Gateway request data, such as a chat or completion...
61
1,572
mlflow
mlflow/gateway/constants.py
.py
from enum import Enum MLFLOW_GATEWAY_CALLER_HEADER = "X-MLflow-Gateway-Caller" MLFLOW_GATEWAY_AUTH_HEADER = "X-MLflow-Authorization" MLFLOW_GATEWAY_DURATION_HEADER = "X-MLflow-Gateway-Duration-Ms" MLFLOW_GATEWAY_OVERHEAD_HEADER = "X-MLflow-Gateway-Overhead-Duration-Ms" class GatewayCaller(str, Enum): """Known ca...
51
2,182
mlflow
mlflow/gateway/provider_registry.py
.py
import logging from mlflow import MlflowException from mlflow.gateway.config import Provider from mlflow.gateway.providers import BaseProvider from mlflow.utils.plugins import get_entry_points from mlflow.utils.provider_filter import is_provider_allowed _logger = logging.getLogger(__name__) class ProviderRegistry: ...
108
4,890
mlflow
mlflow/gateway/guardrail_utils.py
.py
from __future__ import annotations import dataclasses import logging from typing import TYPE_CHECKING, Any from fastapi import Request from mlflow.entities.gateway_guardrail import GuardrailStage from mlflow.gateway.guardrails import JudgeGuardrail from mlflow.gateway.schemas import chat from mlflow.server.asgi_util...
127
4,802
mlflow
mlflow/gateway/cli.py
.py
import click from mlflow.environment_variables import MLFLOW_GATEWAY_CONFIG from mlflow.gateway.config import _validate_config from mlflow.gateway.runner import run_app from mlflow.telemetry.events import GatewayStartEvent from mlflow.telemetry.track import _record_event from mlflow.utils.annotations import deprecated...
57
1,624
mlflow
mlflow/gateway/config.py
.py
import json import logging import os import pathlib from enum import Enum from pathlib import Path from typing import TYPE_CHECKING, Any, Literal import pydantic import yaml from pydantic import ConfigDict, ValidationError, field_validator, model_validator from pydantic.json import pydantic_encoder from mlflow.enviro...
662
22,487
mlflow
mlflow/gateway/budget.py
.py
"""Budget tracking and enforcement for the MLflow Gateway. This module provides budget-related functions for recording costs, refreshing policies, firing exceeded-budget webhooks, and creating on_complete callbacks for budget recording. """ import logging from fastapi import HTTPException import mlflow from mlflow....
232
8,695
mlflow
mlflow/gateway/schemas/__init__.py
.py
from mlflow.gateway.schemas import chat, completions, embeddings __all__ = ["chat", "completions", "embeddings"]
4
114
mlflow
mlflow/gateway/schemas/chat.py
.py
""" This module defines the schemas for the MLflow AI Gateway's chat endpoint. The schemas must be compatible with OpenAI's Chat Completion API. https://platform.openai.com/docs/api-reference/chat NB: These Pydantic models just alias the models defined in mlflow.types.chat to avoid code duplication, but with the ...
137
4,232
mlflow
mlflow/gateway/schemas/embeddings.py
.py
from pydantic import ConfigDict from mlflow.gateway.base_models import RequestModel, ResponseModel _REQUEST_PAYLOAD_EXTRA_SCHEMA = { "example": { "input": ["hello", "world"], } } class RequestPayload(RequestModel): input: str | list[str] | list[int] | list[list[int]] model_config = ConfigDi...
89
2,199
mlflow
mlflow/gateway/schemas/completions.py
.py
from pydantic import ConfigDict from mlflow.gateway.base_models import RequestModel, ResponseModel from mlflow.types.chat import BaseRequestPayload _REQUEST_PAYLOAD_EXTRA_SCHEMA = { "example": { "prompt": "hello", "temperature": 0.0, "max_tokens": 64, "stop": ["END"], "n": ...
98
2,329
mlflow
mlflow/gateway/budget_tracker/__init__.py
.py
"""Budget tracker for AI Gateway cost management. Provides an abstract BudgetTracker interface and window computation helpers. The concrete InMemoryBudgetTracker lives in ``budget_tracker.in_memory``. """ from __future__ import annotations import threading import time from abc import ABC, abstractmethod from datacla...
256
9,435
mlflow
mlflow/gateway/budget_tracker/in_memory.py
.py
"""In-memory budget tracker implementation.""" from __future__ import annotations import threading from dataclasses import dataclass, field from datetime import datetime, timezone from mlflow.entities.gateway_budget_policy import BudgetAction, GatewayBudgetPolicy from mlflow.gateway.budget_tracker import ( Budge...
165
6,035
mlflow
mlflow/gateway/budget_tracker/redis.py
.py
"""Redis-backed budget tracker implementation.""" from __future__ import annotations import json import logging from dataclasses import dataclass, field from datetime import datetime, timezone from typing import TYPE_CHECKING if TYPE_CHECKING: import redis from mlflow.entities.gateway_budget_policy import ( ...
359
12,137
mlflow
mlflow/gateway/providers/openai.py
.py
import json import os import warnings from typing import TYPE_CHECKING, Any, AsyncIterable from urllib.parse import urlparse, urlunparse from mlflow.environment_variables import MLFLOW_ENABLE_UC_FUNCTIONS from mlflow.exceptions import MlflowException from mlflow.gateway.config import EndpointConfig, OpenAIAPIType, Ope...
676
26,250
mlflow
mlflow/gateway/providers/sap_ai_core.py
.py
"""SAP AI Core Orchestration v2 provider for MLflow Gateway. URI scheme: ``sap-ai-core:/<model-name>`` The model name is embedded in the Orchestration v2 request body under ``config.modules.prompt_templating.model.name``. Auth is not handled here — requests are routed through an HTTP egress gateway (``http://`` sche...
173
6,334
mlflow
mlflow/gateway/providers/mosaicml.py
.py
import time import warnings from contextlib import contextmanager from typing import Any from mlflow.exceptions import MlflowException from mlflow.gateway.config import EndpointConfig, MosaicMLConfig from mlflow.gateway.exceptions import AIGatewayException from mlflow.gateway.providers.base import BaseProvider from ml...
308
10,648
mlflow
mlflow/gateway/providers/vertex_ai.py
.py
""" Vertex AI provider for MLflow AI Gateway. Extends the Gemini provider to use Vertex AI endpoints with Google Cloud authentication (Application Default Credentials or service account JSON). Three model types are supported: - **Google models** (gemini-*, medlm-*, text-embedding-*, etc.): Gemini API format with :...
317
12,708
mlflow
mlflow/gateway/providers/utils.py
.py
import re import time from contextlib import asynccontextmanager from contextvars import ContextVar from typing import Any, AsyncGenerator from urllib.parse import urlparse, urlunparse from mlflow.environment_variables import MLFLOW_GATEWAY_ROUTE_TIMEOUT_SECONDS from mlflow.gateway.constants import MLFLOW_GATEWAY_AUTH...
245
10,066
mlflow
mlflow/gateway/providers/gemini.py
.py
import hashlib import json import time from typing import Any, AsyncIterable from mlflow.gateway.config import EndpointConfig, GeminiConfig from mlflow.gateway.exceptions import AIGatewayException from mlflow.gateway.providers.base import ( BaseProvider, PassthroughAction, ProviderAdapter, _client_prov...
981
35,829