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/genai/git_versioning/__init__.py | .py | import logging
from typing_extensions import Self
import mlflow
from mlflow.genai.git_versioning.git_info import GitInfo, GitOperationError
from mlflow.telemetry.events import GitModelVersioningEvent
from mlflow.telemetry.track import record_usage_event
from mlflow.tracking.fluent import _set_active_model
from mlflow... | 162 | 5,382 |
mlflow | mlflow/genai/git_versioning/git_info.py | .py | import logging
from dataclasses import dataclass
from typing_extensions import Self
from mlflow.utils.mlflow_tags import (
MLFLOW_GIT_BRANCH,
MLFLOW_GIT_COMMIT,
MLFLOW_GIT_DIFF,
MLFLOW_GIT_DIRTY,
MLFLOW_GIT_REPO_URL,
)
_logger = logging.getLogger(__name__)
class GitOperationError(Exception):
... | 101 | 3,276 |
mlflow | mlflow/genai/prompts/utils.py | .py | import re
from typing import Any
def format_prompt(prompt: str, **values: Any) -> str:
"""Format double-curly variables in the prompt template."""
for key, value in values.items():
# Escape backslashes in the replacement string to prevent re.sub from interpreting
# them as escape sequences (e.... | 13 | 508 |
mlflow | mlflow/genai/prompts/__init__.py | .py | import json
import warnings
from contextlib import contextmanager
from typing import Any
from pydantic import BaseModel
import mlflow.tracking._model_registry.fluent as registry_api
from mlflow.entities.model_registry.prompt import Prompt
from mlflow.entities.model_registry.prompt_version import (
PromptModelConf... | 415 | 14,905 |
mlflow | mlflow/genai/datasets/databricks_evaluation_dataset_source.py | .py | from typing import Any
from mlflow.data.dataset_source import DatasetSource
class DatabricksEvaluationDatasetSource(DatasetSource):
"""
Represents a Databricks Evaluation Dataset source.
This source is used for datasets managed by the Databricks agents SDK.
"""
def __init__(
self,
... | 103 | 3,057 |
mlflow | mlflow/genai/datasets/evaluation_dataset.py | .py | from datetime import datetime
from typing import TYPE_CHECKING, Any
from mlflow.data import Dataset
from mlflow.data.pyfunc_dataset_mixin import PyFuncConvertibleDatasetMixin
from mlflow.entities.evaluation_dataset import (
EvaluationDataset as _EntityEvaluationDataset,
)
from mlflow.genai.datasets.databricks_eval... | 360 | 13,412 |
mlflow | mlflow/genai/datasets/__init__.py | .py | """
Databricks Agent Datasets Python SDK. For more details see Databricks Agent Evaluation:
<https://docs.databricks.com/en/generative-ai/agent-evaluation/index.html>
The API docs can be found here:
<https://api-docs.databricks.com/python/databricks-agents/latest/databricks_agent_eval.html#datasets>
"""
import loggi... | 798 | 28,145 |
mlflow | mlflow/genai/datasets/entities.py | .py | from dataclasses import dataclass
from datetime import datetime, timedelta
def _format_datetime_for_repr(value: datetime) -> str:
formatted = value.isoformat(sep=" ", timespec="seconds")
if value.utcoffset() == timedelta(0):
return formatted.removesuffix("+00:00") + " UTC"
return formatted
@data... | 33 | 941 |
mlflow | mlflow/genai/evaluation/rate_limiter.py | .py | """Thread-safe rate limiters for evaluation harness."""
from __future__ import annotations
import abc
import contextlib
import logging
import threading
import time
from typing import Callable
_logger = logging.getLogger(__name__)
@contextlib.contextmanager
def eval_retry_context():
"""Disable downstream 429 re... | 194 | 6,570 |
mlflow | mlflow/genai/evaluation/telemetry.py | .py | import hashlib
import threading
import uuid
import mlflow
from mlflow.genai.scorers.base import Scorer
from mlflow.genai.scorers.builtin_scorers import BuiltInScorer
from mlflow.utils.databricks_utils import get_databricks_host_creds
from mlflow.utils.rest_utils import _REST_API_PATH_PREFIX, http_request
from mlflow.u... | 142 | 4,375 |
mlflow | mlflow/genai/evaluation/utils.py | .py | import json
import logging
import math
from typing import TYPE_CHECKING, Any, Collection
from mlflow.entities import Assessment, Trace, TraceData
from mlflow.entities.assessment import DEFAULT_FEEDBACK_NAME, Feedback
from mlflow.entities.assessment_source import AssessmentSource, AssessmentSourceType
from mlflow.entit... | 467 | 16,696 |
mlflow | mlflow/genai/evaluation/__init__.py | .py | from mlflow.genai.evaluation.base import evaluate, to_predict_fn
__all__ = ["evaluate", "to_predict_fn"]
| 4 | 106 |
mlflow | mlflow/genai/evaluation/entities.py | .py | """Entities for evaluation."""
import hashlib
import json
from dataclasses import dataclass, field
from typing import Any, Callable
import pandas as pd
from mlflow.entities.assessment import Expectation, Feedback
from mlflow.entities.assessment_source import AssessmentSource, AssessmentSourceType
from mlflow.entitie... | 338 | 12,121 |
mlflow | mlflow/genai/evaluation/session_utils.py | .py | """Utilities for session-level (multi-turn) evaluation."""
from __future__ import annotations
import traceback
from collections import defaultdict
from concurrent.futures import ThreadPoolExecutor
from typing import TYPE_CHECKING, Any
from mlflow.entities.assessment import Feedback
from mlflow.entities.assessment_er... | 211 | 7,657 |
mlflow | mlflow/genai/evaluation/context.py | .py | """
Introduces main Context class and the framework to specify different specialized
contexts.
"""
import functools
from abc import ABC, abstractmethod
from typing import Callable, ParamSpec, TypeVar
import mlflow
from mlflow.tracking.context import registry as context_registry
from mlflow.utils.mlflow_tags import ML... | 146 | 4,020 |
mlflow | mlflow/genai/evaluation/job.py | .py | """Huey job function for the UI-triggered `mlflow.genai.evaluate` flow.
This module backs the `POST /ajax-api/3.0/mlflow/genai/evaluate/invoke` endpoint
used by the "Run evaluation" modal's "Run judges" button.
"""
import logging
import os
import mlflow
from mlflow.client import MlflowClient
from mlflow.entities.run... | 61 | 2,118 |
mlflow | mlflow/genai/evaluation/constant.py | .py | class AgentEvaluationReserverKey:
"""
Expectation column names that are used by Agent Evaluation.
Ref: https://docs.databricks.com/aws/en/generative-ai/agent-evaluation/evaluation-schema
"""
EXPECTED_RESPONSE = "expected_response"
EXPECTED_RETRIEVED_CONTEXT = "expected_retrieved_context"
EX... | 48 | 1,260 |
mlflow | mlflow/genai/evaluation/base.py | .py | import inspect
import logging
import os
import time
from contextlib import nullcontext
from typing import TYPE_CHECKING, Any, Callable, NamedTuple
import mlflow
from mlflow.data.dataset import Dataset
from mlflow.entities.dataset_input import DatasetInput
from mlflow.entities.evaluation_dataset import EvaluationDatase... | 715 | 28,358 |
mlflow | mlflow/genai/evaluation/harness.py | .py | """Entry point to the evaluation harness"""
from __future__ import annotations
import logging
import queue
import threading
import time
import traceback
import uuid
from concurrent.futures import FIRST_COMPLETED, Future, ThreadPoolExecutor, as_completed, wait
from typing import Any, Callable
import pandas as pd
try... | 1,120 | 41,605 |
mlflow | mlflow/genai/agent_server/server.py | .py | import argparse
import functools
import inspect
import json
import logging
import os
import posixpath
from typing import Any, AsyncGenerator, Callable, Literal, ParamSpec, TypeVar
import httpx
import uvicorn
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import Response, StreamingResponse
... | 439 | 17,247 |
mlflow | mlflow/genai/agent_server/utils.py | .py | import logging
import os
import subprocess
from contextvars import ContextVar
from mlflow.tracking.fluent import _set_active_model
# Context-isolated storage for request headers
# ensuring thread-safe access across async execution contexts
_request_headers: ContextVar[dict[str, str]] = ContextVar[dict[str, str]](
... | 48 | 1,656 |
mlflow | mlflow/genai/agent_server/__init__.py | .py | from mlflow.genai.agent_server.server import (
AgentServer,
get_invoke_function,
get_stream_function,
invoke,
stream,
)
from mlflow.genai.agent_server.utils import (
get_request_headers,
set_request_headers,
setup_mlflow_git_based_version_tracking,
)
__all__ = [
"set_request_headers... | 24 | 500 |
mlflow | mlflow/genai/agent_server/validator.py | .py | from dataclasses import asdict, is_dataclass
from typing import Any
from pydantic import BaseModel
from mlflow.types.responses import (
ResponsesAgentRequest,
ResponsesAgentResponse,
ResponsesAgentStreamEvent,
)
class BaseAgentValidator:
"""Base validator class with common validation methods"""
... | 67 | 2,527 |
mlflow | mlflow/genai/label_schemas/label_schemas.py | .py | import warnings
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import TYPE_CHECKING, TypeVar
from mlflow.exceptions import MlflowException
from mlflow.genai.utils.enum_utils import StrEnum
from mlflow.protos import label_schemas_pb2 as _ls_pb
from mlflow.protos.databricks_pb2 import ... | 465 | 17,937 |
mlflow | mlflow/genai/label_schemas/__init__.py | .py | """
Label schemas define how reviewers annotate traces in the review UI.
By default a schema is managed in the MLflow tracking store and scoped to an
experiment (identity ``(experiment_id, name)``, with a server-generated
``schema_id``). On a Databricks tracking URI the same functions route to the
workspace's ReviewAp... | 318 | 11,349 |
mlflow | mlflow/genai/label_schemas/validation.py | .py | """
Server-side validation for label schemas.
Type immutability post-create is enforced server-side (the field is
documented as immutable but the entity does not enforce it on its own).
The validation surface is intentionally split:
- :py:func:`validate_schema_for_create` is called from the store layer's
create pa... | 320 | 12,453 |
mlflow | mlflow/genai/utils/type.py | .py | from __future__ import annotations
from typing import Any
from mlflow.types.chat import Function
class FunctionCall(Function):
arguments: str | dict[str, Any] | None = None
outputs: Any | None = None
exception: str | None = None
| 12 | 245 |
mlflow | mlflow/genai/utils/llm_utils.py | .py | from __future__ import annotations
import functools
import logging
import threading
import time
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any
import pydantic
import requests
import mlflow
from mlflow.gateway.config import EndpointType
from mlflow.genai.judges.adapters.litellm_adapter import... | 278 | 9,894 |
mlflow | mlflow/genai/utils/enum_utils.py | .py | from enum import Enum, EnumMeta
class MetaEnum(EnumMeta):
"""Metaclass for Enum classes that allows to check if a value is a valid member of the Enum."""
def __contains__(cls, item):
try:
cls(item)
except ValueError:
return False
return True
class StrEnum(str... | 24 | 635 |
mlflow | mlflow/genai/utils/message_utils.py | .py | from __future__ import annotations
from typing import Any
from pydantic import BaseModel
_JSON_SCHEMA_MAP_KEYWORDS = {
"$defs",
"definitions",
"dependencies",
"dependentSchemas",
"patternProperties",
"properties",
}
def serialize_messages_to_prompts(
messages: list[Any],
) -> tuple[str,... | 133 | 4,266 |
mlflow | mlflow/genai/utils/trace_utils.py | .py | import asyncio
import functools
import inspect
import json
import logging
import math
import threading
from collections import OrderedDict
from typing import TYPE_CHECKING, Any, Callable
from cachetools.func import cached
from opentelemetry.trace import NoOpTracer
from pydantic import BaseModel, Field
import mlflow
f... | 1,283 | 47,111 |
mlflow | mlflow/genai/utils/gateway_utils.py | .py | from __future__ import annotations
import base64
from dataclasses import dataclass
from mlflow.environment_variables import MLFLOW_GATEWAY_URI
from mlflow.exceptions import MlflowException
from mlflow.tracking import get_tracking_uri
from mlflow.utils.credentials import read_mlflow_creds
from mlflow.utils.uri import ... | 114 | 4,114 |
mlflow | mlflow/genai/utils/display_utils.py | .py | import sys
from mlflow.entities import Run
from mlflow.store.tracking.rest_store import RestStore
from mlflow.tracing.display.display_handler import _is_jupyter
from mlflow.tracking._tracking_service.utils import _get_store, get_tracking_uri
from mlflow.utils.mlflow_tags import MLFLOW_DATABRICKS_WORKSPACE_URL
from mlf... | 157 | 4,953 |
mlflow | mlflow/genai/utils/data_validation.py | .py | import inspect
import logging
from typing import Any, Callable
from mlflow.exceptions import MlflowException
from mlflow.tracing.provider import trace_disabled
_logger = logging.getLogger(__name__)
def check_model_prediction(predict_fn: Callable[..., Any], sample_input: Any):
"""
Validate if the predict fun... | 149 | 5,071 |
mlflow | mlflow/genai/utils/prompts/available_tools_extraction.py | .py | from typing import TYPE_CHECKING
if TYPE_CHECKING:
from mlflow.types.llm import ChatMessage
AVAILABLE_TOOLS_EXTRACTION_SYSTEM_PROMPT = """You are an expert in analyzing agent execution traces.
Your task is to examine an MLflow trace and identify all tools or functions that were
available to the LLM, not which too... | 105 | 3,960 |
mlflow | mlflow/genai/optimize/types.py | .py | import multiprocessing
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any, Callable
from mlflow.entities import Feedback, Trace
from mlflow.entities.model_registry import PromptVersion
from mlflow.utils.annotations import deprecated
if TYPE_CHECKING:
from mlflow.genai.optimize.optimize... | 152 | 6,084 |
mlflow | mlflow/genai/optimize/optimize.py | .py | import json
import logging
import uuid
from concurrent.futures import ThreadPoolExecutor
from contextlib import nullcontext
from typing import TYPE_CHECKING, Any, Callable
import mlflow
from mlflow.entities import Trace
from mlflow.entities.evaluation_dataset import EvaluationDataset as EntityEvaluationDataset
from ml... | 402 | 17,321 |
mlflow | mlflow/genai/optimize/util.py | .py | from __future__ import annotations
import functools
from contextlib import contextmanager, nullcontext
from typing import TYPE_CHECKING, Any, Callable
from pydantic import BaseModel, create_model
from mlflow.entities import Trace
from mlflow.exceptions import MlflowException
from mlflow.genai.scorers import Scorer
f... | 217 | 8,385 |
mlflow | mlflow/genai/optimize/__init__.py | .py | from mlflow.exceptions import MlflowException
from mlflow.genai.optimize.optimize import optimize_prompts
from mlflow.genai.optimize.optimizers import (
BasePromptOptimizer,
GepaPromptOptimizer,
MetaPromptOptimizer,
)
from mlflow.genai.optimize.types import (
LLMParams,
OptimizerConfig,
PromptOp... | 106 | 3,532 |
mlflow | mlflow/genai/optimize/job.py | .py | import logging
from dataclasses import asdict, dataclass
from enum import Enum
from typing import Any, Callable
from mlflow.exceptions import INVALID_PARAMETER_VALUE, MlflowException
from mlflow.genai.datasets import get_dataset
from mlflow.genai.optimize import optimize_prompts
from mlflow.genai.optimize.optimizers i... | 322 | 12,142 |
mlflow | mlflow/genai/optimize/optimizers/metaprompt_optimizer.py | .py | import json
import logging
import re
from contextlib import nullcontext
from typing import Any
import mlflow
from mlflow.entities.span import SpanType
from mlflow.exceptions import MlflowException
from mlflow.genai.optimize.optimizers.base import BasePromptOptimizer, _EvalFunc
from mlflow.genai.optimize.types import E... | 698 | 28,105 |
mlflow | mlflow/genai/optimize/optimizers/gepa_optimizer.py | .py | import json
import logging
import tempfile
from pathlib import Path
from typing import TYPE_CHECKING, Any
import mlflow
from mlflow.exceptions import MlflowException
from mlflow.genai.optimize.optimizers.base import BasePromptOptimizer, _EvalFunc
from mlflow.genai.optimize.types import EvaluationResultRecord, PromptOp... | 418 | 17,149 |
mlflow | mlflow/genai/optimize/optimizers/base.py | .py | from abc import ABC, abstractmethod
from typing import Any, Callable
from mlflow.genai.optimize.types import EvaluationResultRecord, PromptOptimizerOutput
# The evaluation function that takes candidate prompts as a dict
# (prompt template name -> prompt template) and a dataset as a list of dicts,
# and returns a list... | 39 | 1,700 |
mlflow | mlflow/genai/review_queues/__init__.py | .py | """Review queues for expert trace-review workflows.
A ``ReviewQueue`` is a named bundle of attached items, a set of
questions (label schemas), and a set of assigned users, scoped to an
experiment. Two flavors of the same entity:
- a **user queue** (``name`` = a user, exactly that one user, all of the
experiment's s... | 284 | 9,462 |
mlflow | mlflow/genai/review_queues/review_queues.py | .py | from dataclasses import dataclass, field
from mlflow.exceptions import MlflowException
from mlflow.genai.utils.enum_utils import StrEnum
from mlflow.protos import review_queues_pb2 as _rq_pb
from mlflow.protos.databricks_pb2 import INVALID_PARAMETER_VALUE
from mlflow.utils.annotations import experimental
@experiment... | 224 | 8,140 |
mlflow | mlflow/genai/review_queues/validation.py | .py | """Server-side validation and normalization for review queues.
Called from the store layer's create / update / attach / status paths.
Length caps on the validated identity fields (queue name, user, schema id,
item id) are aligned with their SQL column widths so a value that passes
validation also fits its column. The ... | 256 | 10,043 |
mlflow | mlflow/genai/labeling/stores.py | .py | """
Labeling store functionality for MLflow GenAI.
This module provides store implementations to manage labeling sessions and schemas
"""
import warnings
from abc import ABCMeta, abstractmethod
from typing import TYPE_CHECKING, Any, Callable
from mlflow.entities import Trace
from mlflow.exceptions import MlflowExcep... | 490 | 18,164 |
mlflow | mlflow/genai/labeling/__init__.py | .py | """
Databricks Agent Labeling Python SDK. For more details see Databricks Agent Evaluation:
<https://docs.databricks.com/en/generative-ai/agent-evaluation/index.html>
The API docs can be found here:
<https://api-docs.databricks.com/python/databricks-agents/latest/databricks_agent_eval.html#review-app>
"""
from typing... | 134 | 4,360 |
mlflow | mlflow/genai/labeling/databricks_utils.py | .py | """
Databricks utilities for MLflow GenAI labeling functionality.
"""
_ERROR_MSG = (
"The `databricks-agents` package is required to use labeling functionality. "
"Please install it with `pip install databricks-agents`."
)
def get_databricks_review_app(experiment_id: str | None = None):
"""Import databri... | 19 | 564 |
mlflow | mlflow/genai/labeling/labeling.py | .py | from typing import TYPE_CHECKING, Any, Iterable, Union
from mlflow.entities import Trace
from mlflow.exceptions import MlflowException
from mlflow.protos.databricks_pb2 import INVALID_PARAMETER_VALUE
if TYPE_CHECKING:
import pandas as pd
from databricks.agents.review_app import (
LabelSchema as _Label... | 316 | 10,355 |
mlflow | mlflow/genai/discovery/clustering.py | .py | from __future__ import annotations
import json
import logging
from pydantic import BaseModel as _BaseModel
from mlflow.entities.issue import IssueSeverity
from mlflow.genai.discovery.constants import (
CLUSTER_LABELS_PROMPT_TEMPLATE,
_format_cluster_categories,
build_cluster_summary_prompt,
)
from mlflow... | 219 | 7,874 |
mlflow | mlflow/genai/discovery/pipeline.py | .py | from __future__ import annotations
import json
import logging
import time
from collections.abc import Callable
from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import dataclass
import pydantic
import mlflow
from mlflow.entities.assessment_source import AssessmentSource, AssessmentSour... | 855 | 30,896 |
mlflow | mlflow/genai/discovery/utils.py | .py | from __future__ import annotations
import logging
from collections import defaultdict
import mlflow
from mlflow.entities.assessment import Feedback
from mlflow.entities.trace import Trace
from mlflow.genai.discovery.constants import (
TRACE_CONTENT_TRUNCATION,
)
from mlflow.genai.discovery.entities import Issue, ... | 272 | 9,454 |
mlflow | mlflow/genai/discovery/extraction.py | .py | from __future__ import annotations
import logging
from collections import defaultdict
from concurrent.futures import ThreadPoolExecutor, as_completed
from mlflow.entities.span import Span, SpanType
from mlflow.entities.span_status import SpanStatusCode
from mlflow.entities.trace import Trace
from mlflow.environment_v... | 303 | 11,627 |
mlflow | mlflow/genai/discovery/sampling.py | .py | from __future__ import annotations
import logging
import random
import mlflow
from mlflow.entities.trace import Trace
from mlflow.genai.discovery.constants import (
SAMPLE_POOL_MULTIPLIER,
SAMPLE_RANDOM_SEED,
)
from mlflow.genai.discovery.utils import group_traces_by_session
_logger = logging.getLogger(__nam... | 65 | 1,980 |
mlflow | mlflow/genai/discovery/__init__.py | .py | from mlflow.genai.discovery.entities import DiscoverIssuesResult, Issue
__all__ = ["DiscoverIssuesResult", "Issue"]
| 4 | 117 |
mlflow | mlflow/genai/discovery/constants.py | .py | from __future__ import annotations
from mlflow.entities.issue import IssueSeverity
# Number of sessions (or individual traces) to sample for triage by default
DEFAULT_TRIAGE_SAMPLE_SIZE = 100
# Fetch N * sample_size traces so random sampling has enough diversity
SAMPLE_POOL_MULTIPLIER = 5
SAMPLE_RANDOM_SEED = 42
# LL... | 407 | 19,881 |
mlflow | mlflow/genai/discovery/entities.py | .py | from __future__ import annotations
from dataclasses import dataclass, field
import pydantic
from mlflow.entities.issue import Issue, IssueSeverity
from mlflow.entities.trace import Trace
from mlflow.genai.discovery.constants import RATIONALE_TRUNCATION_LIMIT
@dataclass
class _TriageResult:
failing_traces: list... | 84 | 2,894 |
mlflow | mlflow/genai/discovery/job.py | .py | from mlflow.client import MlflowClient
from mlflow.entities.run_status import RunStatus
from mlflow.environment_variables import MLFLOW_SERVER_JUDGE_INVOKE_MAX_WORKERS
from mlflow.exceptions import MlflowException
from mlflow.genai.discovery.pipeline import discover_issues
from mlflow.server.jobs import job
from mlflow... | 83 | 3,225 |
mlflow | mlflow/config/__init__.py | .py | from mlflow.environment_variables import (
MLFLOW_ENABLE_ASYNC_LOGGING,
)
from mlflow.system_metrics import (
disable_system_metrics_logging,
enable_system_metrics_logging,
set_system_metrics_node_id,
set_system_metrics_samples_before_logging,
set_system_metrics_sampling_interval,
)
from mlflow.... | 57 | 1,456 |
mlflow | mlflow/statsmodels/__init__.py | .py | """
The ``mlflow.statsmodels`` module provides an API for logging and loading statsmodels models.
This module exports statsmodels models with the following flavors:
statsmodels (native) format
This is the main flavor that can be loaded back into statsmodels, which relies on pickle
internally to serialize a mod... | 635 | 23,717 |
mlflow | mlflow/rfunc/__init__.py | .py | """Export and import of generic R models.
This module defines generic filesystem format for R models and provides utilities
for saving and loading to and from this format. The format is self contained in the sense
that it includes all necessary information for anyone to load it and use it. Dependencies
are either stor... | 43 | 1,138 |
mlflow | mlflow/rfunc/backend.py | .py | import logging
import os
import re
import subprocess
import sys
from mlflow.exceptions import MlflowException
from mlflow.models import FlavorBackend
from mlflow.tracking.artifact_utils import _download_artifact_from_uri
_logger = logging.getLogger(__name__)
class RFuncBackend(FlavorBackend):
"""
Flavor bac... | 146 | 4,147 |
mlflow | mlflow/spark/__init__.py | .py | """
The ``mlflow.spark`` module provides an API for logging and loading Spark MLlib models. This module
exports Spark MLlib models with the following flavors:
Spark MLlib (native) format
Allows models to be loaded as Spark Transformers for scoring in a Spark session.
Models with this flavor can be loaded as Py... | 1,291 | 54,795 |
mlflow | mlflow/spark/autologging.py | .py | import concurrent.futures
import logging
import sys
import threading
import uuid
from py4j.java_gateway import CallbackServerParameters
from mlflow import MlflowClient
from mlflow.exceptions import MlflowException
from mlflow.spark import FLAVOR_NAME
from mlflow.tracking.context.abstract_context import RunContextProv... | 301 | 11,603 |
mlflow | mlflow/pyfunc/_mlflow_pyfunc_backend_predict.py | .py | """
This script should be executed in a fresh python interpreter process using `subprocess`.
"""
import argparse
from mlflow.pyfunc.scoring_server import _predict
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("--model-uri", required=True)
parser.add_argument("--input-path", re... | 62 | 1,928 |
mlflow | mlflow/pyfunc/spark_model_cache.py | .py | from mlflow.utils._spark_utils import _SparkDirectoryDistributor
class SparkModelCache:
"""Caches models in memory on Spark Executors, to avoid continually reloading from disk.
This class has to be part of a different module than the one that _uses_ it. This is
because Spark will pickle classes that are ... | 49 | 2,091 |
mlflow | mlflow/pyfunc/model.py | .py | """
The ``mlflow.pyfunc.model`` module defines logic for saving and loading custom "python_function"
models with a user-defined ``PythonModel`` subclass.
"""
import bz2
import gzip
import inspect
import logging
import lzma
import os
import shutil
from abc import ABCMeta, abstractmethod
from collections.abc import Sequ... | 1,667 | 73,266 |
mlflow | mlflow/pyfunc/__init__.py | .py | """
The ``python_function`` model flavor serves as a default model interface for MLflow Python models.
Any MLflow Python model is expected to be loadable as a ``python_function`` model.
In addition, the ``mlflow.pyfunc`` module defines a generic :ref:`filesystem format
<pyfunc-filesystem-format>` for Python models and... | 3,997 | 170,947 |
mlflow | mlflow/pyfunc/stdin_server.py | .py | import argparse
import inspect
import json
import logging
import sys
from mlflow.pyfunc import scoring_server
from mlflow.pyfunc.model import _log_warning_if_params_not_in_predict_signature
_logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
parser = argparse.ArgumentParser()
parser.add_arg... | 45 | 1,362 |
mlflow | mlflow/pyfunc/dbconnect_artifact_cache.py | .py | import json
import os
import subprocess
import tarfile
from pathlib import Path
from mlflow.exceptions import MlflowException
from mlflow.utils.databricks_utils import is_in_databricks_runtime
from mlflow.utils.file_utils import check_tarfile_security, get_or_create_tmp_dir
_CACHE_MAP_FILE_NAME = "db_connect_artifact... | 166 | 6,672 |
mlflow | mlflow/pyfunc/context.py | .py | import contextlib
from contextvars import ContextVar
from dataclasses import dataclass
from typing import Any
# A thread local variable to store the context of the current prediction request.
# This is particularly used to associate logs/traces with a specific prediction request in the
# caller side. The context varia... | 79 | 2,967 |
mlflow | mlflow/pyfunc/backend.py | .py | import ctypes
import json
import logging
import os
import pathlib
import shlex
import signal
import subprocess
import sys
import warnings
from pathlib import Path
from mlflow import pyfunc
from mlflow.exceptions import MlflowException
from mlflow.models import FlavorBackend, Model, docker_utils
from mlflow.models.dock... | 518 | 20,832 |
mlflow | mlflow/pyfunc/scoring_server/app.py | .py | import os
from mlflow.pyfunc import scoring_server
app = scoring_server.init(
scoring_server.load_model_with_mlflow_config(os.environ[scoring_server._SERVER_MODEL_PATH])
)
| 8 | 178 |
mlflow | mlflow/pyfunc/scoring_server/__init__.py | .py | """
Scoring server for python model format.
The passed int model is expected to have function:
predict(pandas.Dataframe) -> pandas.DataFrame
Input, expected in text/csv or application/json format,
is parsed into pandas.DataFrame and passed to the model.
Defines four endpoints:
/ping used for health check
/... | 580 | 21,249 |
mlflow | mlflow/pyfunc/scoring_server/client.py | .py | import json
import logging
import tempfile
import time
import uuid
from abc import ABC, abstractmethod
from pathlib import Path
from typing import Any
import requests
from mlflow.deployments import PredictionsResponse
from mlflow.environment_variables import MLFLOW_SCORING_SERVER_REQUEST_TIMEOUT
from mlflow.exception... | 152 | 5,432 |
mlflow | mlflow/pyfunc/loaders/code_model.py | .py | from typing import Any
from mlflow.pyfunc.loaders.chat_agent import _ChatAgentPyfuncWrapper
from mlflow.pyfunc.loaders.chat_model import _ChatModelPyfuncWrapper
from mlflow.pyfunc.model import (
ChatAgent,
ChatModel,
_load_context_model_and_signature,
_PythonModelPyfuncWrapper,
)
try:
from mlflow.... | 32 | 1,121 |
mlflow | mlflow/pyfunc/loaders/chat_model.py | .py | import inspect
import logging
from typing import Any, Generator
from mlflow.exceptions import MlflowException
from mlflow.models.utils import _convert_llm_ndarray_to_list
from mlflow.protos.databricks_pb2 import INTERNAL_ERROR
from mlflow.pyfunc.model import (
_load_context_model_and_signature,
)
from mlflow.types... | 126 | 5,130 |
mlflow | mlflow/pyfunc/loaders/responses_agent.py | .py | from typing import Any, Generator
import pydantic
from mlflow.exceptions import MlflowException
from mlflow.models.utils import _convert_llm_ndarray_to_list
from mlflow.protos.databricks_pb2 import INTERNAL_ERROR
from mlflow.pyfunc.model import _load_context_model_and_signature
from mlflow.types.responses import (
... | 104 | 4,053 |
mlflow | mlflow/pyfunc/loaders/chat_agent.py | .py | from typing import Any, Generator
import pydantic
from mlflow.exceptions import MlflowException
from mlflow.models.utils import _convert_llm_ndarray_to_list
from mlflow.protos.databricks_pb2 import INTERNAL_ERROR
from mlflow.pyfunc.model import (
_load_context_model_and_signature,
)
from mlflow.types.agent import... | 116 | 4,436 |
mlflow | mlflow/pyfunc/utils/environment.py | .py | import os
from contextlib import contextmanager
from mlflow.environment_variables import _MLFLOW_IS_IN_SERVING_ENVIRONMENT
@contextmanager
def _simulate_serving_environment():
"""
Some functions (e.g. validate_serving_input) replicate the data transformation logic
that happens in the model serving enviro... | 23 | 824 |
mlflow | mlflow/pyfunc/utils/__init__.py | .py | from mlflow.pyfunc.utils.data_validation import pyfunc
__all__ = ["pyfunc"]
| 4 | 77 |
mlflow | mlflow/pyfunc/utils/serving_data_parser.py | .py | from typing import Any
# Support unwrapped JSON with these keys for LLM use cases of Chat, Completions, Embeddings tasks
LLM_CHAT_KEY = "messages"
LLM_COMPLETIONS_KEY = "prompt"
LLM_EMBEDDINGS_KEY = "input"
SUPPORTED_LLM_FORMATS = {LLM_CHAT_KEY, LLM_COMPLETIONS_KEY, LLM_EMBEDDINGS_KEY}
def is_unified_llm_input(json_... | 12 | 407 |
mlflow | mlflow/pyfunc/utils/input_converter.py | .py | from dataclasses import fields, is_dataclass
from types import UnionType
from typing import Union, get_args, get_origin
def _is_optional_dataclass(field_type) -> bool:
"""
Check if the field type is an Optional containing a dataclass.
Currently, ... | None (in Python 3.10) is not supported.
"""
if... | 46 | 1,949 |
mlflow | mlflow/pyfunc/utils/data_validation.py | .py | import inspect
import warnings
from functools import lru_cache, wraps
from typing import Any, NamedTuple
import pydantic
from mlflow.exceptions import MlflowException
from mlflow.models.signature import (
_extract_type_hints,
_is_context_in_predict_function_signature,
)
from mlflow.types.type_hints import (
... | 226 | 8,709 |
mlflow | mlflow/ai_commands/ai_command_utils.py | .py | """Core module for managing MLflow commands."""
import os
import re
from pathlib import Path
from typing import Any
import yaml
def parse_frontmatter(content: str) -> tuple[dict[str, Any], str]:
"""Parse frontmatter from markdown content.
Args:
content: Markdown content with optional YAML frontmatt... | 118 | 3,329 |
mlflow | mlflow/ai_commands/__init__.py | .py | """CLI commands for managing MLflow AI commands."""
import click
from mlflow.ai_commands.ai_command_utils import (
get_command,
get_command_body,
list_commands,
parse_frontmatter,
)
from mlflow.telemetry.events import AiCommandRunEvent
from mlflow.telemetry.track import _record_event
__all__ = ["get_... | 71 | 2,010 |
mlflow | mlflow/openai/api_request_parallel_processor.py | .py | # Based ons: https://github.com/openai/openai-cookbook/blob/6df6ceff470eeba26a56de131254e775292eac22/examples/api_request_parallel_processor.py
# Several changes were made to make it work with MLflow.
"""
API REQUEST PARALLEL PROCESSOR
Using the OpenAI API to process lots of text quickly takes some care.
If you trick... | 132 | 4,392 |
mlflow | mlflow/openai/_agent_tracer.py | .py | from __future__ import annotations
import json
import logging
import weakref
from typing import Any
import agents.tracing as oai
from agents import add_trace_processor, set_trace_processors
from agents.tracing.setup import get_trace_provider
from mlflow.entities.span import LiveSpan, SpanType
from mlflow.entities.sp... | 443 | 16,342 |
mlflow | mlflow/openai/model.py | .py | import itertools
import logging
import os
import warnings
from functools import partial
from string import Formatter
from typing import Any
import yaml
import mlflow
from mlflow import pyfunc
from mlflow.entities.model_registry.prompt import Prompt
from mlflow.environment_variables import MLFLOW_OPENAI_SECRET_SCOPE
f... | 871 | 31,958 |
mlflow | mlflow/openai/__init__.py | .py | """
The ``mlflow.openai`` module provides an API for logging and loading OpenAI models.
Credential management for OpenAI on Databricks
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. warning::
Specifying secrets for model serving with ``MLFLOW_OPENAI_SECRET_SCOPE`` is deprecated.
Use `secrets-based environ... | 58 | 2,010 |
mlflow | mlflow/openai/autolog.py | .py | import json
import logging
from typing import Any, AsyncIterator, Iterator
import mlflow
from mlflow.entities import SpanType
from mlflow.entities.span import LiveSpan
from mlflow.entities.span_event import SpanEvent
from mlflow.entities.span_status import SpanStatusCode
from mlflow.exceptions import MlflowException
f... | 550 | 21,030 |
mlflow | mlflow/openai/genai_semconv_converter.py | .py | """
OpenAI-format message converters for GenAI Semantic Convention export.
Two converters handle the two OpenAI API shapes:
- OpenAIChatCompletionConverter: Chat Completions API (also used by Groq, Bedrock)
- OpenAIResponsesConverter: Responses API
"""
import json
from typing import Any
from mlflow.tracing.constant ... | 268 | 10,341 |
mlflow | mlflow/openai/utils/chat_schema.py | .py | import logging
from collections.abc import Iterable
from typing import Any
from mlflow.entities.span import LiveSpan
from mlflow.exceptions import MlflowException
from mlflow.tracing import set_span_chat_tools
from mlflow.tracing.constant import SpanAttributeKey, TokenUsageKey
from mlflow.tracing.utils import set_span... | 232 | 7,153 |
mlflow | mlflow/anthropic/__init__.py | .py | import logging
from mlflow.anthropic.autolog import (
async_patched_class_call,
patched_class_call,
patched_claude_sdk_init,
)
from mlflow.telemetry.events import AutologgingEvent
from mlflow.telemetry.track import _record_event
from mlflow.utils.autologging_utils import autologging_integration, safe_patch... | 66 | 1,973 |
mlflow | mlflow/anthropic/chat.py | .py | import json
from typing import Any
from pydantic import BaseModel
from mlflow.exceptions import MlflowException
from mlflow.types.chat import (
ChatMessage,
ChatTool,
Function,
FunctionToolDefinition,
ImageContentPart,
ImageUrl,
TextContentPart,
ToolCall,
)
def convert_message_to_mlf... | 138 | 5,256 |
mlflow | mlflow/anthropic/autolog.py | .py | import logging
from typing import Any
import mlflow.anthropic
from mlflow.anthropic.chat import convert_tool_to_mlflow_chat_tool
from mlflow.entities import SpanType
from mlflow.entities.span import LiveSpan
from mlflow.tracing.constant import SpanAttributeKey, TokenUsageKey
from mlflow.tracing.distributed import _get... | 204 | 8,186 |
mlflow | mlflow/anthropic/genai_semconv_converter.py | .py | import json
from typing import Any
from mlflow.tracing.constant import GenAiSemconvKey
from mlflow.tracing.export.genai_semconv.converter import GenAiSemconvConverter
class AnthropicConverter(GenAiSemconvConverter):
def convert_inputs(self, inputs: dict[str, Any]) -> list[dict[str, Any]] | None:
messages... | 102 | 3,971 |
mlflow | mlflow/sentence_transformers/__init__.py | .py | import json
import logging
import pathlib
import re
from typing import Any
import numpy as np
import pandas as pd
import yaml
from packaging.version import Version
import mlflow
from mlflow import pyfunc
from mlflow.entities.model_registry.prompt import Prompt
from mlflow.exceptions import MlflowException
from mlflow... | 566 | 22,418 |
mlflow | mlflow/optuna/storage.py | .py | import copy
import datetime
import json
import threading
import time
import uuid
import weakref
from collections.abc import Container, Sequence
from typing import Any
from mlflow import MlflowClient
from mlflow.entities import Metric, Param, RunTag
from mlflow.utils.mlflow_tags import MLFLOW_PARENT_RUN_ID
try:
fr... | 663 | 25,313 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.