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/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
mlflow
mlflow/optuna/__init__.py
.py
from mlflow.optuna.storage import MlflowStorage __all__ = ["MlflowStorage"]
4
77
mlflow
mlflow/metrics/__init__.py
.py
import os from mlflow.metrics import genai from mlflow.metrics.base import MetricValue from mlflow.metrics.genai.utils import _MIGRATION_GUIDE from mlflow.metrics.metric_definitions import ( _accuracy_eval_fn, _ari_eval_fn, _bleu_eval_fn, _f1_score_eval_fn, _flesch_kincaid_eval_fn, _mae_eval_fn...
512
16,829
mlflow
mlflow/metrics/metric_definitions.py
.py
import functools import logging import subprocess import tempfile from pathlib import Path import numpy as np from mlflow.environment_variables import _MLFLOW_TESTING from mlflow.metrics.base import MetricValue, standard_aggregations _logger = logging.getLogger(__name__) # used to silently fail with invalid metric...
594
21,315
mlflow
mlflow/metrics/base.py
.py
from dataclasses import dataclass import numpy as np from mlflow.utils.validation import _is_numeric def standard_aggregations(scores): return { "mean": np.mean(scores), "variance": np.var(scores), "p90": np.percentile(scores, 90), } @dataclass class MetricValue: """ The va...
39
1,015
mlflow
mlflow/metrics/genai/prompt_template.py
.py
import string from typing import Any class PromptTemplate: """A prompt template for a language model. A prompt template consists of an array of strings that will be concatenated together. It accepts a set of parameters from the user that can be used to generate a prompt for a language model. The tem...
69
2,441
mlflow
mlflow/metrics/genai/utils.py
.py
_MIGRATION_GUIDE = ( "Use the new GenAI evaluation functionality instead. See " "https://mlflow.org/docs/latest/genai/eval-monitor/legacy-llm-evaluation/ " "for the migration guide." ) def _get_latest_metric_version(): return "v1" def _get_default_model(): return "openai:/gpt-4"
14
304
mlflow
mlflow/metrics/genai/__init__.py
.py
from mlflow.metrics.genai.base import EvaluationExample from mlflow.metrics.genai.genai_metric import ( make_genai_metric, make_genai_metric_from_prompt, retrieve_custom_metrics, ) from mlflow.metrics.genai.metric_definitions import ( answer_correctness, answer_relevance, answer_similarity, ...
26
596
mlflow
mlflow/metrics/genai/genai_metric.py
.py
import json import logging import re import warnings from concurrent.futures import ThreadPoolExecutor, as_completed from inspect import Parameter, Signature from tempfile import TemporaryDirectory from typing import Any import pandas as pd import mlflow from mlflow.exceptions import MlflowException from mlflow.metri...
807
33,307
mlflow
mlflow/metrics/genai/metric_definitions.py
.py
from typing import Any from mlflow.exceptions import MlflowException from mlflow.metrics.genai.base import EvaluationExample from mlflow.metrics.genai.genai_metric import make_genai_metric from mlflow.metrics.genai.utils import _MIGRATION_GUIDE, _get_latest_metric_version from mlflow.models import EvaluationMetric fro...
457
23,122
mlflow
mlflow/metrics/genai/model_utils.py
.py
import logging import os from typing import TYPE_CHECKING, Any import requests from pydantic import BaseModel from mlflow.environment_variables import MLFLOW_GENAI_EVAL_LLM_TIMEOUT from mlflow.exceptions import MlflowException from mlflow.gateway.config import EndpointConfig from mlflow.gateway.providers.openai impor...
639
25,017
mlflow
mlflow/metrics/genai/base.py
.py
from dataclasses import dataclass from mlflow.metrics.genai.prompt_template import PromptTemplate @dataclass class EvaluationExample: """ Stores the sample example during few shot learning during LLM evaluation Args: input: The input provided to the model output: The output generated by ...
99
3,819
mlflow
mlflow/metrics/genai/prompts/v1.py
.py
from dataclasses import dataclass, field from typing import Any from mlflow.metrics.genai.base import EvaluationExample from mlflow.metrics.genai.prompt_template import PromptTemplate # TODO: Update the default_mode and default_parameters to the correct values post experimentation default_model = "openai:/gpt-4" # De...
458
22,799
mlflow
mlflow/mcp/server.py
.py
import contextlib import io import os from typing import TYPE_CHECKING, Any, Callable import click from click.types import BOOL, FLOAT, INT, STRING, UUID import mlflow.deployments.cli as deployments_cli import mlflow.experiments import mlflow.models.cli as models_cli import mlflow.runs from mlflow.ai_commands.ai_comm...
256
8,485
mlflow
mlflow/mcp/decorator.py
.py
""" Decorator for exposing MLflow CLI commands as MCP tools. Usage: from mlflow.mcp.decorator import mlflow_mcp @commands.command("search") @mlflow_mcp(tool_name="search_traces") @click.option(...) def search_traces(...): ... The decorator attaches MCP metadata to the Click command, which...
75
2,043
mlflow
mlflow/mcp/cli.py
.py
import click from mlflow.mcp.server import run_server from mlflow.telemetry.events import McpRunEvent from mlflow.telemetry.track import record_usage_event @click.group( "mcp", help=( "Model Context Protocol (MCP) server for MLflow. " "MCP enables LLM applications to interact with MLflow trac...
34
872
mlflow
mlflow/utils/_unity_catalog_oss_utils.py
.py
import re from mlflow.entities.model_registry import ( ModelVersion, ModelVersionSearch, RegisteredModel, RegisteredModelSearch, ) from mlflow.exceptions import MlflowException from mlflow.protos.unity_catalog_messages_pb2 import ( ModelVersionInfo, ModelVersionStatus, RegisteredModelInfo, ...
97
3,440
mlflow
mlflow/utils/spark_utils.py
.py
def is_spark_connect_mode(): try: from pyspark.sql.utils import is_remote except ImportError: return False return is_remote() def get_spark_dataframe_type(): if is_spark_connect_mode(): from pyspark.sql.connect.dataframe import DataFrame as SparkDataFrame else: from...
16
395
mlflow
mlflow/utils/env_pack.py
.py
import shutil import subprocess import sys import tarfile import tempfile from contextlib import contextmanager from dataclasses import dataclass from pathlib import Path from typing import Generator, Literal import yaml from mlflow.artifacts import download_artifacts from mlflow.exceptions import MlflowException fro...
216
7,998
mlflow
mlflow/utils/lazy_load.py
.py
"""Utility to lazy load modules.""" import importlib import sys import types class LazyLoader(types.ModuleType): """Class for module lazy loading. This class helps lazily load modules at package level, which avoids pulling in large dependencies like `tensorflow` or `torch`. This class is mirrored from w...
52
1,726
mlflow
mlflow/utils/process.py
.py
import functools import os import subprocess import sys from mlflow.utils.databricks_utils import is_in_databricks_runtime from mlflow.utils.os import is_windows class ShellCommandException(Exception): @classmethod def from_completed_process(cls, process): lines = [ f"Non-zero exit code: ...
182
6,522
mlflow
mlflow/utils/exception_utils.py
.py
import traceback def get_stacktrace(error): msg = repr(error) try: tb = traceback.format_exception(error) return (msg + "".join(tb)).strip() except Exception: return msg
11
208
mlflow
mlflow/utils/oss_registry_utils.py
.py
import urllib.parse from mlflow.environment_variables import MLFLOW_UC_OSS_TOKEN from mlflow.exceptions import MlflowException from mlflow.utils.databricks_utils import get_databricks_host_creds from mlflow.utils.rest_utils import MlflowHostCreds from mlflow.utils.uri import ( _DATABRICKS_UNITY_CATALOG_SCHEME, ) ...
30
936
mlflow
mlflow/utils/name_utils.py
.py
import random import uuid _EXPERIMENT_ID_FIXED_WIDTH = 18 def _generate_unique_integer_id(): """Utility function for generating a random fixed-length integer Returns: a fixed-width integer """ random_int = uuid.uuid4().int # Cast to string to get a fixed length random_str = str(rand...
343
5,763
mlflow
mlflow/utils/_spark_utils.py
.py
import contextlib import multiprocessing import os import shutil import tempfile import zipfile def _get_active_spark_session(): try: from pyspark.sql import SparkSession except ImportError: # Return None if user doesn't have PySpark installed return None try: # getActiveSe...
203
8,065
mlflow
mlflow/utils/timeout.py
.py
import signal from contextlib import contextmanager from mlflow.exceptions import MlflowException from mlflow.protos.databricks_pb2 import NOT_IMPLEMENTED from mlflow.utils.os import is_windows class MlflowTimeoutError(Exception): pass @contextmanager def run_with_timeout(seconds): """ Context manager ...
43
1,214
mlflow
mlflow/utils/class_utils.py
.py
import importlib def _get_class_from_string(fully_qualified_class_name): module, class_name = fully_qualified_class_name.rsplit(".", maxsplit=1) return getattr(importlib.import_module(module), class_name)
7
215
mlflow
mlflow/utils/virtualenv.py
.py
import logging import os import re import shutil import tempfile import uuid from pathlib import Path from typing import Literal from packaging.version import Version import mlflow from mlflow.environment_variables import _MLFLOW_TESTING, MLFLOW_ENV_ROOT from mlflow.exceptions import MlflowException from mlflow.model...
463
18,821
mlflow
mlflow/utils/search_utils.py
.py
import ast import base64 import json import math import operator import re import shlex from dataclasses import asdict, dataclass from typing import TYPE_CHECKING, Any, Callable import sqlparse from packaging.version import Version from sqlparse.sql import ( Comparison, Identifier, Parenthesis, Stateme...
2,888
118,188