code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def _parse_outputs(outputs) -> list[ChatMessage]:
"""
This method extract chat messages from genai.types.generation_types.GenerateContentResponse
"""
# content always exist on output
# https://github.com/googleapis/googleapis/blob/9e966149c59f47f6305d66c98e2a9e7d9c26a2eb/google/ai/generativelanguage... |
This method extract chat messages from genai.types.generation_types.GenerateContentResponse
| _parse_outputs | python | mlflow/mlflow | mlflow/gemini/autolog.py | https://github.com/mlflow/mlflow/blob/master/mlflow/gemini/autolog.py | Apache-2.0 |
def _log_generativeai_tool_definition(model, span):
"""
This method extract tool definition from generativeai tool type.
"""
# when tools are not passed
if not getattr(model, "_tools", None):
return
try:
set_span_chat_tools(
span,
[
conver... |
This method extract tool definition from generativeai tool type.
| _log_generativeai_tool_definition | python | mlflow/mlflow | mlflow/gemini/autolog.py | https://github.com/mlflow/mlflow/blob/master/mlflow/gemini/autolog.py | Apache-2.0 |
def _log_genai_tool_definition(model, inputs, span):
"""
This method extract tool definition from genai tool type.
"""
config = inputs.get("config")
tools = getattr(config, "tools", None)
if not tools:
return
# Here, we use an internal function of gemini library to convert callable t... |
This method extract tool definition from genai tool type.
| _log_genai_tool_definition | python | mlflow/mlflow | mlflow/gemini/autolog.py | https://github.com/mlflow/mlflow/blob/master/mlflow/gemini/autolog.py | Apache-2.0 |
def convert_gemini_func_to_mlflow_chat_tool(
function_def: "genai.types.FunctionDeclaration",
) -> ChatTool:
"""
Convert Gemini function definition into MLflow's standard format (OpenAI compatible).
Ref: https://ai.google.dev/gemini-api/docs/function-calling
Args:
function_def: A genai.type... |
Convert Gemini function definition into MLflow's standard format (OpenAI compatible).
Ref: https://ai.google.dev/gemini-api/docs/function-calling
Args:
function_def: A genai.types.FunctionDeclaration or genai.protos.FunctionDeclaration object
representing a function definitio... | convert_gemini_func_to_mlflow_chat_tool | python | mlflow/mlflow | mlflow/gemini/chat.py | https://github.com/mlflow/mlflow/blob/master/mlflow/gemini/chat.py | Apache-2.0 |
def convert_gemini_func_call_to_mlflow_tool_call(
func_call: "genai.types.FunctionCall",
) -> ToolCall:
"""
Convert Gemini function call into MLflow's standard format (OpenAI compatible).
Ref: https://ai.google.dev/gemini-api/docs/function-calling
Args:
func_call: A genai.types.FunctionCall... |
Convert Gemini function call into MLflow's standard format (OpenAI compatible).
Ref: https://ai.google.dev/gemini-api/docs/function-calling
Args:
func_call: A genai.types.FunctionCall or genai.protos.FunctionCall object
representing a single func call.
Returns:
Tool... | convert_gemini_func_call_to_mlflow_tool_call | python | mlflow/mlflow | mlflow/gemini/chat.py | https://github.com/mlflow/mlflow/blob/master/mlflow/gemini/chat.py | Apache-2.0 |
def parse_gemini_content_to_mlflow_chat_messages(
content: "genai.types.ContentsType",
) -> list[ChatMessage]:
"""
Convert a gemini content to chat messages.
Args:
content: A genai.types.ContentsType object representing the model content.
Returns:
list[ChatMessage]: A list of MLflo... |
Convert a gemini content to chat messages.
Args:
content: A genai.types.ContentsType object representing the model content.
Returns:
list[ChatMessage]: A list of MLflow's standard chat messages.
| parse_gemini_content_to_mlflow_chat_messages | python | mlflow/mlflow | mlflow/gemini/chat.py | https://github.com/mlflow/mlflow/blob/master/mlflow/gemini/chat.py | Apache-2.0 |
def _parse_content_part(part: "genai.types.PartType") -> Optional[Union[TextContentPart, ToolCall]]:
"""
Convert Gemini part type into MLflow's standard format (OpenAI compatible).
Ref: https://ai.google.dev/gemini-api/docs/function-calling
Args:
part: A genai.types.PartType object representing... |
Convert Gemini part type into MLflow's standard format (OpenAI compatible).
Ref: https://ai.google.dev/gemini-api/docs/function-calling
Args:
part: A genai.types.PartType object representing a part of content.
Returns:
Optional[Union[TextContentPart, ToolCall]]: MLflow's standard cont... | _parse_content_part | python | mlflow/mlflow | mlflow/gemini/chat.py | https://github.com/mlflow/mlflow/blob/master/mlflow/gemini/chat.py | Apache-2.0 |
def _convert_gemini_param_property_to_mlflow_param_property(param_property) -> ParamProperty:
"""
Convert Gemini parameter property definition into MLflow's standard format (OpenAI compatible).
Ref: https://ai.google.dev/gemini-api/docs/function-calling
Args:
param_property: A genai.types.Schem... |
Convert Gemini parameter property definition into MLflow's standard format (OpenAI compatible).
Ref: https://ai.google.dev/gemini-api/docs/function-calling
Args:
param_property: A genai.types.Schema or genai.protos.Schema object
representing a parameter property.
Retur... | _convert_gemini_param_property_to_mlflow_param_property | python | mlflow/mlflow | mlflow/gemini/chat.py | https://github.com/mlflow/mlflow/blob/master/mlflow/gemini/chat.py | Apache-2.0 |
def _convert_gemini_function_param_to_mlflow_function_param(
function_params: "genai.types.Schema",
) -> FunctionParams:
"""
Convert Gemini function parameter definition into MLflow's standard format (OpenAI compatible).
Ref: https://ai.google.dev/gemini-api/docs/function-calling
Args:
func... |
Convert Gemini function parameter definition into MLflow's standard format (OpenAI compatible).
Ref: https://ai.google.dev/gemini-api/docs/function-calling
Args:
function_params: A genai.types.Schema or genai.protos.Schema object
representing function parameters.
Retu... | _convert_gemini_function_param_to_mlflow_function_param | python | mlflow/mlflow | mlflow/gemini/chat.py | https://github.com/mlflow/mlflow/blob/master/mlflow/gemini/chat.py | Apache-2.0 |
def autolog(
log_traces: bool = True,
disable: bool = False,
silent: bool = False,
):
"""
Enables (or disables) and configures autologging from Gemini to MLflow.
Currently, both legacy SDK google-generativeai and new SDK google-genai are supported.
Only synchronous calls are supported. Async... |
Enables (or disables) and configures autologging from Gemini to MLflow.
Currently, both legacy SDK google-generativeai and new SDK google-genai are supported.
Only synchronous calls are supported. Asynchnorous APIs and streaming are not recorded.
Args:
log_traces: If ``True``, traces are logge... | autolog | python | mlflow/mlflow | mlflow/gemini/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/gemini/__init__.py | Apache-2.0 |
def add_scheduled_scorer( # clint: disable=missing-docstring-param # noqa: D417
*,
scheduled_scorer_name: str,
scorer: Scorer,
sample_rate: float,
filter_string: Optional[str] = None,
experiment_id: Optional[str] = None,
**kwargs,
) -> ScorerScheduleConfig:
"""
Add a scheduled scor... |
Add a scheduled scorer to automatically monitor traces in an MLflow experiment.
This function configures a scorer function to run automatically on traces logged to the
specified experiment. The scorer will evaluate a sample of traces based on the sampling rate
and any filter criteria. Assessments are ... | add_scheduled_scorer | python | mlflow/mlflow | mlflow/genai/scheduled_scorers.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/scheduled_scorers.py | Apache-2.0 |
def delete_scheduled_scorer( # clint: disable=missing-docstring-param # noqa: D417
*,
scheduled_scorer_name: str,
experiment_id: Optional[str] = None,
**kwargs,
) -> None:
"""
Delete a scheduled scorer from an MLflow experiment.
This function removes a scheduled scorer configuration, stop... |
Delete a scheduled scorer from an MLflow experiment.
This function removes a scheduled scorer configuration, stopping automatic evaluation
of traces. Existing Assessments will remain in the Traces tab of the MLflow
experiment, but no new evaluations will be performed.
Args:
scheduled_scor... | delete_scheduled_scorer | python | mlflow/mlflow | mlflow/genai/scheduled_scorers.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/scheduled_scorers.py | Apache-2.0 |
def get_scheduled_scorer( # clint: disable=missing-docstring-param # noqa: D417
*,
scheduled_scorer_name: str,
experiment_id: Optional[str] = None,
**kwargs,
) -> ScorerScheduleConfig:
"""
Retrieve the configuration of a specific scheduled scorer.
This function returns the current configu... |
Retrieve the configuration of a specific scheduled scorer.
This function returns the current configuration of a scheduled scorer, including
its scorer function, sampling rate, and filter criteria.
Args:
scheduled_scorer_name: The name of the scheduled scorer to retrieve.
experiment_id... | get_scheduled_scorer | python | mlflow/mlflow | mlflow/genai/scheduled_scorers.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/scheduled_scorers.py | Apache-2.0 |
def list_scheduled_scorers( # clint: disable=missing-docstring-param # noqa: D417
*, experiment_id: Optional[str] = None, **kwargs
) -> list[ScorerScheduleConfig]:
"""
List all scheduled scorers for an experiment.
This function returns all scheduled scorers configured for the specified experiment,
... |
List all scheduled scorers for an experiment.
This function returns all scheduled scorers configured for the specified experiment,
or for the current active experiment if no experiment ID is provided.
Args:
experiment_id: The ID of the MLflow experiment to list scheduled scorers for.
... | list_scheduled_scorers | python | mlflow/mlflow | mlflow/genai/scheduled_scorers.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/scheduled_scorers.py | Apache-2.0 |
def set_scheduled_scorers( # clint: disable=missing-docstring-param # noqa: D417
*,
scheduled_scorers: list[ScorerScheduleConfig],
experiment_id: Optional[str] = None,
**kwargs,
) -> None:
"""
Replace all scheduled scorers for an experiment with the provided list.
This function removes al... |
Replace all scheduled scorers for an experiment with the provided list.
This function removes all existing scheduled scorers for the specified experiment
and replaces them with the new list. This is useful for batch configuration updates
or when you want to ensure only specific scorers are active.
... | set_scheduled_scorers | python | mlflow/mlflow | mlflow/genai/scheduled_scorers.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/scheduled_scorers.py | Apache-2.0 |
def digest(self) -> Optional[str]:
"""String digest (hash) of the dataset provided by the caller that uniquely identifies"""
# NB: The managed Dataset entity in Agent SDK doesn't propagate the digest
# information. So we compute the digest of the dataframe view.
if self._digest is None:
... | String digest (hash) of the dataset provided by the caller that uniquely identifies | digest | python | mlflow/mlflow | mlflow/genai/datasets/evaluation_dataset.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/datasets/evaluation_dataset.py | Apache-2.0 |
def to_df(self) -> "pd.DataFrame":
"""Convert the dataset to a pandas DataFrame."""
# Cache the dataframe view to avoid re-fetching the records many times
if self._df is None:
self._df = self._dataset.to_df()
return self._df | Convert the dataset to a pandas DataFrame. | to_df | python | mlflow/mlflow | mlflow/genai/datasets/evaluation_dataset.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/datasets/evaluation_dataset.py | Apache-2.0 |
def to_evaluation_dataset(self, path=None, feature_names=None) -> LegacyEvaluationDataset:
"""
Converts the dataset to the legacy EvaluationDataset for model evaluation. Required
for use with mlflow.evaluate().
"""
return LegacyEvaluationDataset(
data=self.to_df(),
... |
Converts the dataset to the legacy EvaluationDataset for model evaluation. Required
for use with mlflow.evaluate().
| to_evaluation_dataset | python | mlflow/mlflow | mlflow/genai/datasets/evaluation_dataset.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/datasets/evaluation_dataset.py | Apache-2.0 |
def create_dataset(
uc_table_name: str, experiment_id: Optional[Union[str, list[str]]] = None
) -> "EvaluationDataset":
"""Create a dataset with the given name and associate it with the given experiment.
Args:
uc_table_name: The UC table name of the dataset.
experiment_id: The ID of the exp... | Create a dataset with the given name and associate it with the given experiment.
Args:
uc_table_name: The UC table name of the dataset.
experiment_id: The ID of the experiment to associate the dataset with. If not provided,
the current experiment is inferred from the environment.
| create_dataset | python | mlflow/mlflow | mlflow/genai/datasets/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/datasets/__init__.py | Apache-2.0 |
def delete_dataset(uc_table_name: str) -> None:
"""Delete the dataset with the given name.
Args:
uc_table_name: The UC table name of the dataset.
"""
try:
from databricks.agents.datasets import delete_dataset
except ImportError:
raise ImportError(_ERROR_MSG) from None
re... | Delete the dataset with the given name.
Args:
uc_table_name: The UC table name of the dataset.
| delete_dataset | python | mlflow/mlflow | mlflow/genai/datasets/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/datasets/__init__.py | Apache-2.0 |
def get_dataset(uc_table_name: str) -> "EvaluationDataset":
"""Get the dataset with the given name.
Args:
uc_table_name: The UC table name of the dataset.
"""
try:
from databricks.agents.datasets import get_dataset
except ImportError as e:
raise ImportError(_ERROR_MSG) from ... | Get the dataset with the given name.
Args:
uc_table_name: The UC table name of the dataset.
| get_dataset | python | mlflow/mlflow | mlflow/genai/datasets/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/datasets/__init__.py | Apache-2.0 |
def to_predict_fn(endpoint_uri: str) -> Callable:
"""
Convert an endpoint URI to a predict function.
Args:
endpoint_uri: The endpoint URI to convert.
Returns:
A predict function that can be used to make predictions.
Example:
The following example assumes that the model se... |
Convert an endpoint URI to a predict function.
Args:
endpoint_uri: The endpoint URI to convert.
Returns:
A predict function that can be used to make predictions.
Example:
The following example assumes that the model serving endpoint accepts a JSON
object with a `mess... | to_predict_fn | python | mlflow/mlflow | mlflow/genai/evaluation/base.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/evaluation/base.py | Apache-2.0 |
def _convert_eval_set_to_df(data: "EvaluationDatasetTypes") -> "pd.DataFrame":
"""
Takes in a dataset in the format that `mlflow.genai.evaluate()` expects and
converts it into a pandas DataFrame.
"""
if isinstance(data, list):
# validate that every item in the list is a dict and has inputs a... |
Takes in a dataset in the format that `mlflow.genai.evaluate()` expects and
converts it into a pandas DataFrame.
| _convert_eval_set_to_df | python | mlflow/mlflow | mlflow/genai/evaluation/utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/evaluation/utils.py | Apache-2.0 |
def _convert_to_legacy_eval_set(data: "EvaluationDatasetTypes") -> "pd.DataFrame":
"""
Takes in a dataset in the format that mlflow.genai.evaluate() expects and converts it into
to the current eval-set schema that Agent Evaluation takes in. The transformed schema should
be accepted by mlflow.evaluate().... |
Takes in a dataset in the format that mlflow.genai.evaluate() expects and converts it into
to the current eval-set schema that Agent Evaluation takes in. The transformed schema should
be accepted by mlflow.evaluate().
The expected schema can be found at:
https://docs.databricks.com/aws/en/generativ... | _convert_to_legacy_eval_set | python | mlflow/mlflow | mlflow/genai/evaluation/utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/evaluation/utils.py | Apache-2.0 |
def _deserialize_inputs_and_expectations_column(df: "pd.DataFrame") -> "pd.DataFrame":
"""
Deserialize the `inputs` and `expectations` string columns from the dataframe.
When managed datasets are read as Spark DataFrames, the `inputs` and `expectations` columns
are loaded as string columns of JSON stri... |
Deserialize the `inputs` and `expectations` string columns from the dataframe.
When managed datasets are read as Spark DataFrames, the `inputs` and `expectations` columns
are loaded as string columns of JSON strings. This function deserializes these columns into
dictionaries expected by mlflow.genai.e... | _deserialize_inputs_and_expectations_column | python | mlflow/mlflow | mlflow/genai/evaluation/utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/evaluation/utils.py | Apache-2.0 |
def _extract_request_from_trace(df: "pd.DataFrame") -> "pd.DataFrame":
"""
Add `request` columns to the dataframe if it is not already present.
This is for compatibility with mlflow.evaluate() that requires `request` column.
"""
if "trace" not in df.columns:
return df
if "request" not i... |
Add `request` columns to the dataframe if it is not already present.
This is for compatibility with mlflow.evaluate() that requires `request` column.
| _extract_request_from_trace | python | mlflow/mlflow | mlflow/genai/evaluation/utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/evaluation/utils.py | Apache-2.0 |
def _extract_expectations_from_trace(df: "pd.DataFrame") -> "pd.DataFrame":
"""
Add `expectations` columns to the dataframe from assessments
stored in the traces, if the "expectations" column is not already present.
"""
if "trace" not in df.columns:
return df
expectations_column = []
... |
Add `expectations` columns to the dataframe from assessments
stored in the traces, if the "expectations" column is not already present.
| _extract_expectations_from_trace | python | mlflow/mlflow | mlflow/genai/evaluation/utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/evaluation/utils.py | Apache-2.0 |
def _convert_scorer_to_legacy_metric(scorer: Scorer) -> EvaluationMetric:
"""
Takes in a Scorer object and converts it into a legacy MLflow 2.x
Metric object.
"""
try:
from databricks.agents.evals import metric
except ImportError:
raise ImportError(
"The `databricks-a... |
Takes in a Scorer object and converts it into a legacy MLflow 2.x
Metric object.
| _convert_scorer_to_legacy_metric | python | mlflow/mlflow | mlflow/genai/evaluation/utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/evaluation/utils.py | Apache-2.0 |
def requires_databricks_agents(func):
"""Decorator to check if the `databricks-agents` package is installed."""
@wraps(func)
def wrapper(*args, **kwargs):
try:
import databricks.agents.evals.judges # noqa: F401
except ImportError:
raise ImportError(
... | Decorator to check if the `databricks-agents` package is installed. | requires_databricks_agents | python | mlflow/mlflow | mlflow/genai/judges/databricks.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/judges/databricks.py | Apache-2.0 |
def is_context_relevant(*, request: str, context: Any, name: Optional[str] = None) -> Feedback:
"""
LLM judge determines whether the given context is relevant to the input request.
Args:
request: Input to the application to evaluate, user's question or query.
context: Context to evaluate th... |
LLM judge determines whether the given context is relevant to the input request.
Args:
request: Input to the application to evaluate, user's question or query.
context: Context to evaluate the relevance to the request.
Supports any JSON-serializable object.
name: Optional n... | is_context_relevant | python | mlflow/mlflow | mlflow/genai/judges/databricks.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/judges/databricks.py | Apache-2.0 |
def is_context_sufficient(
*,
request: str,
context: Any,
expected_facts: list[str],
expected_response: Optional[str] = None,
name: Optional[str] = None,
) -> Feedback:
"""
LLM judge determines whether the given context is sufficient to answer the input request.
Args:
reques... |
LLM judge determines whether the given context is sufficient to answer the input request.
Args:
request: Input to the application to evaluate, user's question or query.
context: Context to evaluate the sufficiency of. Supports any JSON-serializable object.
expected_facts: A list of exp... | is_context_sufficient | python | mlflow/mlflow | mlflow/genai/judges/databricks.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/judges/databricks.py | Apache-2.0 |
def is_correct(
*,
request: str,
response: str,
expected_facts: list[str],
expected_response: Optional[str] = None,
name: Optional[str] = None,
) -> Feedback:
"""
LLM judge determines whether the given response is correct for the input request.
Args:
request: Input to the ap... |
LLM judge determines whether the given response is correct for the input request.
Args:
request: Input to the application to evaluate, user's question or query.
response: The response from the application to evaluate.
expected_facts: A list of expected facts that should be present in t... | is_correct | python | mlflow/mlflow | mlflow/genai/judges/databricks.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/judges/databricks.py | Apache-2.0 |
def is_grounded(
*, request: str, response: str, context: Any, name: Optional[str] = None
) -> Feedback:
"""
LLM judge determines whether the given response is grounded in the given context.
Args:
request: Input to the application to evaluate, user's question or query.
response: The res... |
LLM judge determines whether the given response is grounded in the given context.
Args:
request: Input to the application to evaluate, user's question or query.
response: The response from the application to evaluate.
context: Context to evaluate the response against. Supports any JSON... | is_grounded | python | mlflow/mlflow | mlflow/genai/judges/databricks.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/judges/databricks.py | Apache-2.0 |
def is_safe(*, content: str, name: Optional[str] = None) -> Feedback:
"""
LLM judge determines whether the given response is safe.
Args:
content: Text content to evaluate for safety.
name: Optional name for overriding the default name of the returned feedback.
Returns:
A :py:cl... |
LLM judge determines whether the given response is safe.
Args:
content: Text content to evaluate for safety.
name: Optional name for overriding the default name of the returned feedback.
Returns:
A :py:class:`mlflow.entities.assessment.Feedback~` object with a "yes" or "no"
... | is_safe | python | mlflow/mlflow | mlflow/genai/judges/databricks.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/judges/databricks.py | Apache-2.0 |
def custom_prompt_judge(
*,
name: str,
prompt_template: str,
numeric_values: Optional[dict[str, Union[int, float]]] = None,
) -> Callable[..., Feedback]:
"""
Create a custom prompt judge that evaluates inputs using a template.
Example prompt template:
.. code-block::
You will ... |
Create a custom prompt judge that evaluates inputs using a template.
Example prompt template:
.. code-block::
You will look at the response and determine the formality of the response.
<request>{{request}}</request>
<response>{{response}}</response>
You must choose one ... | custom_prompt_judge | python | mlflow/mlflow | mlflow/genai/judges/databricks.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/judges/databricks.py | Apache-2.0 |
def add_dataset(
self, dataset_name: str, record_ids: Optional[list[str]] = None
) -> "LabelingSession":
"""Add a dataset to the labeling session.
.. note::
This functionality is only available in Databricks. Please run
`pip install mlflow[databricks]` to use it.
... | Add a dataset to the labeling session.
.. note::
This functionality is only available in Databricks. Please run
`pip install mlflow[databricks]` to use it.
Args:
dataset_name: The name of the dataset.
record_ids: Optional. The individual record ids to be... | add_dataset | python | mlflow/mlflow | mlflow/genai/labeling/labeling.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/labeling/labeling.py | Apache-2.0 |
def add_traces(
self,
traces: Union[Iterable[Trace], Iterable[str], "pd.DataFrame"],
) -> "LabelingSession":
"""Add traces to the labeling session.
.. note::
This functionality is only available in Databricks. Please run
`pip install mlflow[databricks]` to us... | Add traces to the labeling session.
.. note::
This functionality is only available in Databricks. Please run
`pip install mlflow[databricks]` to use it.
Args:
traces: Can be either:
a) a pandas DataFrame with a 'trace' column. The 'trace' column shou... | add_traces | python | mlflow/mlflow | mlflow/genai/labeling/labeling.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/labeling/labeling.py | Apache-2.0 |
def add_agent(
self, *, agent_name: str, model_serving_endpoint: str, overwrite: bool = False
) -> "ReviewApp":
"""Add an agent to the review app to be used to generate responses.
.. note::
This functionality is only available in Databricks. Please run
`pip install m... | Add an agent to the review app to be used to generate responses.
.. note::
This functionality is only available in Databricks. Please run
`pip install mlflow[databricks]` to use it.
Args:
agent_name: The name of the agent.
model_serving_endpoint: The mod... | add_agent | python | mlflow/mlflow | mlflow/genai/labeling/labeling.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/labeling/labeling.py | Apache-2.0 |
def get_review_app(experiment_id: Optional[str] = None) -> "ReviewApp":
"""Gets or creates (if it doesn't exist) the review app for the given experiment ID.
.. note::
This functionality is only available in Databricks. Please run
`pip install mlflow[databricks]` to use it.
Args:
ex... | Gets or creates (if it doesn't exist) the review app for the given experiment ID.
.. note::
This functionality is only available in Databricks. Please run
`pip install mlflow[databricks]` to use it.
Args:
experiment_id: Optional. The experiment ID for which to get the review app. If no... | get_review_app | python | mlflow/mlflow | mlflow/genai/labeling/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/labeling/__init__.py | Apache-2.0 |
def create_labeling_session(
name: str,
*,
assigned_users: list[str] = [], # noqa: B006
agent: Optional[str] = None,
label_schemas: list[str] = [], # noqa: B006
enable_multi_turn_chat: bool = False,
custom_inputs: Optional[dict[str, Any]] = None,
) -> LabelingSession:
"""Create a new l... | Create a new labeling session in the review app.
.. note::
This functionality is only available in Databricks. Please run
`pip install mlflow[databricks]` to use it.
Args:
name: The name of the labeling session.
assigned_users: The users that will be assigned to label items in ... | create_labeling_session | python | mlflow/mlflow | mlflow/genai/labeling/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/labeling/__init__.py | Apache-2.0 |
def get_labeling_sessions() -> list[LabelingSession]:
"""Get all labeling sessions from the review app.
.. note::
This functionality is only available in Databricks. Please run
`pip install mlflow[databricks]` to use it.
Returns:
list[LabelingSession]: The list of labeling sessions... | Get all labeling sessions from the review app.
.. note::
This functionality is only available in Databricks. Please run
`pip install mlflow[databricks]` to use it.
Returns:
list[LabelingSession]: The list of labeling sessions.
| get_labeling_sessions | python | mlflow/mlflow | mlflow/genai/labeling/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/labeling/__init__.py | Apache-2.0 |
def get_labeling_session(run_id: str) -> LabelingSession:
"""Get a labeling session from the review app.
.. note::
This functionality is only available in Databricks. Please run
`pip install mlflow[databricks]` to use it.
Args:
run_id: The mlflow run ID of the labeling session to g... | Get a labeling session from the review app.
.. note::
This functionality is only available in Databricks. Please run
`pip install mlflow[databricks]` to use it.
Args:
run_id: The mlflow run ID of the labeling session to get.
Returns:
LabelingSession: The labeling session.
... | get_labeling_session | python | mlflow/mlflow | mlflow/genai/labeling/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/labeling/__init__.py | Apache-2.0 |
def delete_labeling_session(labeling_session: LabelingSession) -> "ReviewApp":
"""Delete a labeling session from the review app.
.. note::
This functionality is only available in Databricks. Please run
`pip install mlflow[databricks]` to use it.
Args:
labeling_session: The labeling... | Delete a labeling session from the review app.
.. note::
This functionality is only available in Databricks. Please run
`pip install mlflow[databricks]` to use it.
Args:
labeling_session: The labeling session to delete.
Returns:
ReviewApp: The review app.
| delete_labeling_session | python | mlflow/mlflow | mlflow/genai/labeling/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/labeling/__init__.py | Apache-2.0 |
def _to_databricks_input(self) -> "_InputTextList":
"""Convert to the internal Databricks input type."""
from databricks.agents.review_app import label_schemas as _label_schemas
return _label_schemas.InputTextList(
max_length_each=self.max_length_each, max_count=self.max_count
... | Convert to the internal Databricks input type. | _to_databricks_input | python | mlflow/mlflow | mlflow/genai/label_schemas/label_schemas.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/label_schemas/label_schemas.py | Apache-2.0 |
def _from_databricks_label_schema(cls, schema: "_LabelSchema") -> "LabelSchema":
"""Convert from the internal Databricks label schema type."""
return cls(
name=schema.name,
type=schema.type,
title=schema.title,
input=schema.input._from_databricks_input(),... | Convert from the internal Databricks label schema type. | _from_databricks_label_schema | python | mlflow/mlflow | mlflow/genai/label_schemas/label_schemas.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/label_schemas/label_schemas.py | Apache-2.0 |
def create_label_schema(
name: str,
*,
type: Literal["feedback", "expectation"],
title: str,
input: Union[
InputCategorical,
InputCategoricalList,
InputText,
InputTextList,
InputNumeric,
],
instruction: Optional[str] = None,
enable_comment: bool = ... | Create a new label schema for the review app.
A label schema defines the type of input that stakeholders will provide when labeling items
in the review app.
.. note::
This functionality is only available in Databricks. Please run
`pip install mlflow[databricks]` to use it.
Args:
... | create_label_schema | python | mlflow/mlflow | mlflow/genai/label_schemas/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/label_schemas/__init__.py | Apache-2.0 |
def get_label_schema(name: str) -> LabelSchema:
"""Get a label schema from the review app.
.. note::
This functionality is only available in Databricks. Please run
`pip install mlflow[databricks]` to use it.
Args:
name: The name of the label schema to get.
Returns:
Lab... | Get a label schema from the review app.
.. note::
This functionality is only available in Databricks. Please run
`pip install mlflow[databricks]` to use it.
Args:
name: The name of the label schema to get.
Returns:
LabelSchema: The label schema.
| get_label_schema | python | mlflow/mlflow | mlflow/genai/label_schemas/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/label_schemas/__init__.py | Apache-2.0 |
def delete_label_schema(name: str) -> "ReviewApp":
"""Delete a label schema from the review app.
.. note::
This functionality is only available in Databricks. Please run
`pip install mlflow[databricks]` to use it.
Args:
name: The name of the label schema to delete.
Returns:
... | Delete a label schema from the review app.
.. note::
This functionality is only available in Databricks. Please run
`pip install mlflow[databricks]` to use it.
Args:
name: The name of the label schema to delete.
Returns:
ReviewApp: The review app.
| delete_label_schema | python | mlflow/mlflow | mlflow/genai/label_schemas/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/label_schemas/__init__.py | Apache-2.0 |
def optimize_prompt(
*,
target_llm_params: LLMParams,
prompt: Union[str, PromptVersion],
train_data: "EvaluationDatasetTypes",
scorers: list[Scorer],
objective: Optional[OBJECTIVE_FN] = None,
eval_data: Optional["EvaluationDatasetTypes"] = None,
optimizer_config: Optional[OptimizerConfig... |
Optimize a LLM prompt using the given dataset and evaluation metrics.
The optimized prompt template is automatically registered as a new version of the
original prompt and included in the result.
Currently, this API only supports DSPy's MIPROv2 optimizer.
Args:
target_llm_params: Parameter... | optimize_prompt | python | mlflow/mlflow | mlflow/genai/optimize/base.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/optimize/base.py | Apache-2.0 |
def optimize(
self,
prompt: Prompt,
target_llm_params: LLMParams,
train_data: "pd.DataFrame",
scorers: list[Scorer],
objective: Optional[OBJECTIVE_FN] = None,
eval_data: Optional["pd.DataFrame"] = None,
) -> Prompt:
"""Optimize the given prompt using t... | Optimize the given prompt using the specified configuration.
Args:
prompt: The prompt to optimize.
target_llm_params: Parameters for the agent LLM.
train_data: Training dataset for optimization.
scorers: List of scorers to evaluate the optimization.
o... | optimize | python | mlflow/mlflow | mlflow/genai/optimize/optimizers/base_optimizer.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/optimize/optimizers/base_optimizer.py | Apache-2.0 |
def _maybe_suppress_stdout_stderr(self):
"""Context manager for redirecting stdout/stderr based on verbose setting.
If verbose is False, redirects output to devnull or StringIO.
If verbose is True, doesn't redirect output.
"""
if not self.optimizer_config.verbose:
try... | Context manager for redirecting stdout/stderr based on verbose setting.
If verbose is False, redirects output to devnull or StringIO.
If verbose is True, doesn't redirect output.
| _maybe_suppress_stdout_stderr | python | mlflow/mlflow | mlflow/genai/optimize/optimizers/dspy_mipro_optimizer.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/optimize/optimizers/dspy_mipro_optimizer.py | Apache-2.0 |
def suppress_genai_migration_warning():
"""Suppress the deprecation warning when the api is called from `mlflow.genai` namespace."""
with warnings.catch_warnings():
warnings.filterwarnings(
action="ignore",
category=FutureWarning,
message="The `mlflow.*` API is moved ... | Suppress the deprecation warning when the api is called from `mlflow.genai` namespace. | suppress_genai_migration_warning | python | mlflow/mlflow | mlflow/genai/prompts/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/prompts/__init__.py | Apache-2.0 |
def load_prompt(
name_or_uri: str, version: Optional[Union[str, int]] = None, allow_missing: bool = False
) -> PromptVersion:
"""
Load a :py:class:`Prompt <mlflow.entities.Prompt>` from the MLflow Prompt Registry.
The prompt can be specified by name and version, or by URI.
Args:
name_or_ur... |
Load a :py:class:`Prompt <mlflow.entities.Prompt>` from the MLflow Prompt Registry.
The prompt can be specified by name and version, or by URI.
Args:
name_or_uri: The name of the prompt, or the URI in the format "prompts:/name/version".
version: The version of the prompt (required when us... | load_prompt | python | mlflow/mlflow | mlflow/genai/prompts/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/prompts/__init__.py | Apache-2.0 |
def set_prompt_alias(name: str, alias: str, version: int) -> None:
"""
Set an alias for a :py:class:`Prompt <mlflow.entities.Prompt>` in the MLflow Prompt Registry.
Args:
name: The name of the prompt.
alias: The alias to set for the prompt.
version: The version of the prompt.
E... |
Set an alias for a :py:class:`Prompt <mlflow.entities.Prompt>` in the MLflow Prompt Registry.
Args:
name: The name of the prompt.
alias: The alias to set for the prompt.
version: The version of the prompt.
Example:
.. code-block:: python
import mlflow
# Set ... | set_prompt_alias | python | mlflow/mlflow | mlflow/genai/prompts/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/prompts/__init__.py | Apache-2.0 |
def delete_prompt_alias(name: str, alias: str) -> None:
"""
Delete an alias for a :py:class:`Prompt <mlflow.entities.Prompt>` in the MLflow Prompt Registry.
Args:
name: The name of the prompt.
alias: The alias to delete for the prompt.
"""
with suppress_genai_migration_warning():
... |
Delete an alias for a :py:class:`Prompt <mlflow.entities.Prompt>` in the MLflow Prompt Registry.
Args:
name: The name of the prompt.
alias: The alias to delete for the prompt.
| delete_prompt_alias | python | mlflow/mlflow | mlflow/genai/prompts/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/prompts/__init__.py | Apache-2.0 |
def _extract_source_code_info(self) -> dict:
"""Extract source code information for the original decorated function."""
from mlflow.genai.scorers.scorer_utils import extract_function_body
result = {"call_source": None, "call_signature": None, "original_func_name": None}
# Extract origi... | Extract source code information for the original decorated function. | _extract_source_code_info | python | mlflow/mlflow | mlflow/genai/scorers/base.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/scorers/base.py | Apache-2.0 |
def model_validate(cls, obj: Any) -> "Scorer":
"""Override model_validate to reconstruct scorer from source code."""
if not isinstance(obj, dict):
raise MlflowException.invalid_parameter_value(
f"Invalid scorer data: expected a dictionary, got {type(obj).__name__}. "
... | Override model_validate to reconstruct scorer from source code. | model_validate | python | mlflow/mlflow | mlflow/genai/scorers/base.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/scorers/base.py | Apache-2.0 |
def _reconstruct_decorator_scorer(cls, serialized: SerializedScorer) -> "Scorer":
"""Reconstruct a decorator scorer from serialized data."""
from mlflow.genai.scorers.scorer_utils import recreate_function
# Recreate the original function from source code
recreated_func = recreate_functi... | Reconstruct a decorator scorer from serialized data. | _reconstruct_decorator_scorer | python | mlflow/mlflow | mlflow/genai/scorers/base.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/scorers/base.py | Apache-2.0 |
def __call__(
self,
*,
inputs: Any = None,
outputs: Any = None,
expectations: Optional[dict[str, Any]] = None,
trace: Optional[Trace] = None,
) -> Union[int, float, bool, str, Feedback, list[Feedback]]:
"""
Implement the custom scorer's logic here.
... |
Implement the custom scorer's logic here.
The scorer will be called for each row in the input evaluation dataset.
Your scorer doesn't need to have all the parameters defined in the base
signature. You can define a custom scorer with only the parameters you need.
See the param... | __call__ | python | mlflow/mlflow | mlflow/genai/scorers/base.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/scorers/base.py | Apache-2.0 |
def model_dump(self, **kwargs) -> dict:
"""Override model_dump to handle builtin scorer serialization."""
# Use mode='json' to automatically convert sets to lists for JSON compatibility
from pydantic import BaseModel
pydantic_model_data = BaseModel.model_dump(self, mode="json", **kwargs... | Override model_dump to handle builtin scorer serialization. | model_dump | python | mlflow/mlflow | mlflow/genai/scorers/builtin_scorers.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/scorers/builtin_scorers.py | Apache-2.0 |
def model_validate(cls, obj) -> "BuiltInScorer":
"""Override model_validate to handle builtin scorer deserialization."""
if not isinstance(obj, dict) or "builtin_scorer_class" not in obj:
raise MlflowException.invalid_parameter_value(
f"Invalid builtin scorer data: expected a... | Override model_validate to handle builtin scorer deserialization. | model_validate | python | mlflow/mlflow | mlflow/genai/scorers/builtin_scorers.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/scorers/builtin_scorers.py | Apache-2.0 |
def _compute_span_relevance(
self, span_id: str, request: str, chunks: dict[str, str]
) -> list[Feedback]:
"""Compute the relevance of retrieved context for one retriever span."""
from databricks.agents.evals.judges import chunk_relevance
# Compute relevance for each chunk. Call `ch... | Compute the relevance of retrieved context for one retriever span. | _compute_span_relevance | python | mlflow/mlflow | mlflow/genai/scorers/builtin_scorers.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/scorers/builtin_scorers.py | Apache-2.0 |
def __call__(self, *, trace: Trace) -> list[Feedback]:
"""
Evaluate groundedness of response against retrieved context.
Args:
trace: The trace of the model's execution. Must contains at least one span with
type `RETRIEVER`. MLflow will extract the retrieved context f... |
Evaluate groundedness of response against retrieved context.
Args:
trace: The trace of the model's execution. Must contains at least one span with
type `RETRIEVER`. MLflow will extract the retrieved context from that span.
If multiple spans are found, MLflow... | __call__ | python | mlflow/mlflow | mlflow/genai/scorers/builtin_scorers.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/scorers/builtin_scorers.py | Apache-2.0 |
def __call__(
self,
*,
inputs: dict[str, Any],
outputs: Any,
) -> Feedback:
"""
Evaluate adherence to specified guidelines.
Args:
inputs: A dictionary of input data, e.g. {"question": "What is the capital of France?"}.
outputs: The res... |
Evaluate adherence to specified guidelines.
Args:
inputs: A dictionary of input data, e.g. {"question": "What is the capital of France?"}.
outputs: The response from the model, e.g. "The capital of France is Paris."
Returns:
An :py:class:`mlflow.entities.as... | __call__ | python | mlflow/mlflow | mlflow/genai/scorers/builtin_scorers.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/scorers/builtin_scorers.py | Apache-2.0 |
def __call__(
self,
*,
inputs: dict[str, Any],
outputs: Any,
expectations: Optional[dict[str, Any]] = None,
) -> Feedback:
"""
Evaluate adherence to specified guidelines.
Args:
inputs: A dictionary of input data, e.g. {"question": "What is... |
Evaluate adherence to specified guidelines.
Args:
inputs: A dictionary of input data, e.g. {"question": "What is the capital of France?"}.
outputs: The response from the model, e.g. "The capital of France is Paris."
expectations: A dictionary of expectations for the... | __call__ | python | mlflow/mlflow | mlflow/genai/scorers/builtin_scorers.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/scorers/builtin_scorers.py | Apache-2.0 |
def __call__(self, *, inputs: dict[str, Any], outputs: Any) -> Feedback:
"""
Evaluate relevance to the user's query.
Args:
inputs: A dictionary of input data, e.g. {"question": "What is the capital of France?"}.
outputs: The response from the model, e.g. "The capital of ... |
Evaluate relevance to the user's query.
Args:
inputs: A dictionary of input data, e.g. {"question": "What is the capital of France?"}.
outputs: The response from the model, e.g. "The capital of France is Paris."
Returns:
An :py:class:`mlflow.entities.assess... | __call__ | python | mlflow/mlflow | mlflow/genai/scorers/builtin_scorers.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/scorers/builtin_scorers.py | Apache-2.0 |
def __call__(
self, *, inputs: dict[str, Any], outputs: Any, expectations: dict[str, Any]
) -> Feedback:
"""
Evaluate correctness of the response against expectations.
Args:
inputs: A dictionary of input data, e.g. {"question": "What is the capital of France?"}.
... |
Evaluate correctness of the response against expectations.
Args:
inputs: A dictionary of input data, e.g. {"question": "What is the capital of France?"}.
outputs: The response from the model, e.g. "The capital of France is Paris."
expectations: A dictionary of expec... | __call__ | python | mlflow/mlflow | mlflow/genai/scorers/builtin_scorers.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/scorers/builtin_scorers.py | Apache-2.0 |
def get_all_scorers() -> list[BuiltInScorer]:
"""
Returns a list of all built-in scorers.
Example:
.. code-block:: python
import mlflow
from mlflow.genai.scorers import get_all_scorers
data = [
{
"inputs": {"question": "What is the capital of Franc... |
Returns a list of all built-in scorers.
Example:
.. code-block:: python
import mlflow
from mlflow.genai.scorers import get_all_scorers
data = [
{
"inputs": {"question": "What is the capital of France?"},
"outputs": "The capital of Fran... | get_all_scorers | python | mlflow/mlflow | mlflow/genai/scorers/builtin_scorers.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/scorers/builtin_scorers.py | Apache-2.0 |
def extract_function_body(func: Callable[..., Any]) -> tuple[str, int]:
"""
Extracts the body of a function as a string without the signature or docstring,
dedents the code, and returns the indentation unit used in the function (e.g., 2 or 4 spaces).
"""
source_lines, _ = inspect.getsourcelines(func... |
Extracts the body of a function as a string without the signature or docstring,
dedents the code, and returns the indentation unit used in the function (e.g., 2 or 4 spaces).
| extract_function_body | python | mlflow/mlflow | mlflow/genai/scorers/scorer_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/scorers/scorer_utils.py | Apache-2.0 |
def recreate_function(source: str, signature: str, func_name: str) -> Optional[Callable]:
"""
Recreate a function from its source code, signature, and name.
Args:
source: The function body source code.
signature: The function signature string (e.g., "(inputs, outputs)").
func_name: ... |
Recreate a function from its source code, signature, and name.
Args:
source: The function body source code.
signature: The function signature string (e.g., "(inputs, outputs)").
func_name: The name of the function.
Returns:
The recreated function or None if recreation fail... | recreate_function | python | mlflow/mlflow | mlflow/genai/scorers/scorer_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/scorers/scorer_utils.py | Apache-2.0 |
def validate_scorers(scorers: list[Any]) -> list[Scorer]:
"""
Validate a list of specified scorers.
Args:
scorers: A list of scorers to validate.
Returns:
A list of valid scorers.
"""
from databricks.rag_eval.evaluation.metrics import Metric
if not isinstance(scorers, list... |
Validate a list of specified scorers.
Args:
scorers: A list of scorers to validate.
Returns:
A list of valid scorers.
| validate_scorers | python | mlflow/mlflow | mlflow/genai/scorers/validation.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/scorers/validation.py | Apache-2.0 |
def valid_data_for_builtin_scorers(
data: "pd.DataFrame",
builtin_scorers: list[BuiltInScorer],
predict_fn: Optional[Callable] = None,
) -> None:
"""
Validate that the required columns are present in the data for running the builtin scorers.
Args:
data: The data to validate. This must b... |
Validate that the required columns are present in the data for running the builtin scorers.
Args:
data: The data to validate. This must be a pandas DataFrame converted to
the legacy evaluation set schema via `_convert_to_legacy_eval_set`.
builtin_scorers: The list of builtin scorer... | valid_data_for_builtin_scorers | python | mlflow/mlflow | mlflow/genai/scorers/validation.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/scorers/validation.py | Apache-2.0 |
def check_model_prediction(predict_fn: Callable, sample_input: Any):
"""
Validate if the predict function executes properly with the provided input.
Args:
predict_fn: The predict function to be evaluated.
sample_input: A sample input to the model.
"""
_logger.info("Testing model pre... |
Validate if the predict function executes properly with the provided input.
Args:
predict_fn: The predict function to be evaluated.
sample_input: A sample input to the model.
| check_model_prediction | python | mlflow/mlflow | mlflow/genai/utils/data_validation.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/utils/data_validation.py | Apache-2.0 |
def _validate_function_and_input_compatibility(
predict_fn: Callable, sample_input: dict[str, Any], e: Exception
) -> Callable:
"""
Validate the data format in the input column against the predict_fn.
The input column must contain a dictionary of field names and values. When the
predict_fn is provi... |
Validate the data format in the input column against the predict_fn.
The input column must contain a dictionary of field names and values. When the
predict_fn is provided, the field names must match the arguments of the predict_fn.
| _validate_function_and_input_compatibility | python | mlflow/mlflow | mlflow/genai/utils/data_validation.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/utils/data_validation.py | Apache-2.0 |
def _has_required_keyword_arguments(params: inspect.Signature, required_args: list[str]) -> bool:
"""Check if the function accepts the specified keyword arguments."""
func_args = []
for name, param in params.items():
# If the function has **kwargs, it accepts all keyword arguments
if param.... | Check if the function accepts the specified keyword arguments. | _has_required_keyword_arguments | python | mlflow/mlflow | mlflow/genai/utils/data_validation.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/utils/data_validation.py | Apache-2.0 |
def convert_predict_fn(predict_fn: Callable, sample_input: Any) -> Callable:
"""
Check the predict_fn is callable and add trace decorator if it is not already traced.
"""
with NoOpTracerPatcher() as counter:
check_model_prediction(predict_fn, sample_input)
if counter.count == 0:
pre... |
Check the predict_fn is callable and add trace decorator if it is not already traced.
| convert_predict_fn | python | mlflow/mlflow | mlflow/genai/utils/trace_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/utils/trace_utils.py | Apache-2.0 |
def _get_top_level_retrieval_spans(trace: Trace) -> list[Span]:
"""
Get the top-level retrieval spans in the trace.
Top-level retrieval spans are retrieval spans that are not children of other retrieval spans.
For example, given the following spans:
- Span A (Chain)
- Span B (Retriever)
... |
Get the top-level retrieval spans in the trace.
Top-level retrieval spans are retrieval spans that are not children of other retrieval spans.
For example, given the following spans:
- Span A (Chain)
- Span B (Retriever)
- Span C (Retriever)
- Span D (Retriever)
- Span E (LLM... | _get_top_level_retrieval_spans | python | mlflow/mlflow | mlflow/genai/utils/trace_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/utils/trace_utils.py | Apache-2.0 |
def clean_up_extra_traces(run_id: str, start_time_ms: int):
"""
Clean up noisy traces generated outside predict function.
Evaluation run should only contain traces that is being evaluated or generated by the predict
function. If not, the result will not show the correct list of traces.
Sometimes, t... |
Clean up noisy traces generated outside predict function.
Evaluation run should only contain traces that is being evaluated or generated by the predict
function. If not, the result will not show the correct list of traces.
Sometimes, there are extra traces generated during the evaluation, for example,... | clean_up_extra_traces | python | mlflow/mlflow | mlflow/genai/utils/trace_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/utils/trace_utils.py | Apache-2.0 |
def copy_model_serving_trace_to_eval_run(trace_dict: dict[str, Any]):
"""
Copy a trace returned from model serving endpoint to the evaluation run.
The copied trace will have a new trace ID and location metadata.
Args:
trace_dict: The trace dictionary returned from model serving endpoint.
... |
Copy a trace returned from model serving endpoint to the evaluation run.
The copied trace will have a new trace ID and location metadata.
Args:
trace_dict: The trace dictionary returned from model serving endpoint.
This can be either V2 or V3 trace.
| copy_model_serving_trace_to_eval_run | python | mlflow/mlflow | mlflow/genai/utils/trace_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/genai/utils/trace_utils.py | Apache-2.0 |
def autolog(
log_traces: bool = True,
disable: bool = False,
silent: bool = False,
):
"""
Enables (or disables) and configures autologging from Groq to MLflow.
Only synchronous calls are supported. Asynchnorous APIs and streaming are not recorded.
Args:
log_traces: If ``True``, trac... |
Enables (or disables) and configures autologging from Groq to MLflow.
Only synchronous calls are supported. Asynchnorous APIs and streaming are not recorded.
Args:
log_traces: If ``True``, traces are logged for Groq models. If ``False``, no traces are
collected during inference. Defaul... | autolog | python | mlflow/mlflow | mlflow/groq/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/groq/__init__.py | Apache-2.0 |
def save_model(
h2o_model,
path,
conda_env=None,
code_paths=None,
mlflow_model=None,
settings=None,
signature: ModelSignature = None,
input_example: ModelInputExample = None,
pip_requirements=None,
extra_pip_requirements=None,
metadata=None,
):
"""Save an H2O model to a p... | Save an H2O model to a path on the local file system.
Args:
h2o_model: H2O model to be saved.
path: Local path where the model is to be saved.
conda_env: {{ conda_env }}
code_paths: {{ code_paths }}
mlflow_model: :py:mod:`mlflow.models.Model` this flavor is being added to.
... | save_model | python | mlflow/mlflow | mlflow/h2o/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/h2o/__init__.py | Apache-2.0 |
def log_model(
h2o_model,
artifact_path: Optional[str] = None,
conda_env=None,
code_paths=None,
registered_model_name=None,
signature: ModelSignature = None,
input_example: ModelInputExample = None,
pip_requirements=None,
extra_pip_requirements=None,
metadata=None,
name: Opti... | Log an H2O model as an MLflow artifact for the current run.
Args:
h2o_model: H2O model to be saved.
artifact_path: Deprecated. Use `name` instead.
conda_env: {{ conda_env }}
code_paths: {{ code_paths }}
registered_model_name: If given, create a model version under
... | log_model | python | mlflow/mlflow | mlflow/h2o/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/h2o/__init__.py | Apache-2.0 |
def predict(self, dataframe, params: Optional[dict[str, Any]] = None):
"""
Args:
dataframe: Model input data.
params: Additional parameters to pass to the model for inference.
Returns:
Model predictions.
"""
import h2o
predicted = sel... |
Args:
dataframe: Model input data.
params: Additional parameters to pass to the model for inference.
Returns:
Model predictions.
| predict | python | mlflow/mlflow | mlflow/h2o/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/h2o/__init__.py | Apache-2.0 |
def load_model(model_uri, dst_path=None):
"""Load an H2O model from a local file (if ``run_id`` is ``None``) or a run.
This function expects there is an H2O instance initialised with ``h2o.init``.
Args:
model_uri: The location, in URI format, of the MLflow model. For example:
- ``/Use... | Load an H2O model from a local file (if ``run_id`` is ``None``) or a run.
This function expects there is an H2O instance initialised with ``h2o.init``.
Args:
model_uri: The location, in URI format, of the MLflow model. For example:
- ``/Users/me/path/to/local/model``
- ``relat... | load_model | python | mlflow/mlflow | mlflow/h2o/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/h2o/__init__.py | Apache-2.0 |
def get_default_pip_requirements():
"""
Returns:
A list of default pip requirements for MLflow Models produced by this flavor.
Calls to :func:`save_model()` and :func:`log_model()` produce a pip environment
that, at minimum, contains these requirements.
"""
from johnsnowlabs impo... |
Returns:
A list of default pip requirements for MLflow Models produced by this flavor.
Calls to :func:`save_model()` and :func:`log_model()` produce a pip environment
that, at minimum, contains these requirements.
| get_default_pip_requirements | python | mlflow/mlflow | mlflow/johnsnowlabs/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/johnsnowlabs/__init__.py | Apache-2.0 |
def _save_model_metadata(
dst_dir,
spark_model,
mlflow_model,
conda_env,
code_paths,
signature=None,
input_example=None,
pip_requirements=None,
extra_pip_requirements=None,
remote_model_path=None,
store_license=False,
):
"""
Saves model metadata into the passed-in dir... |
Saves model metadata into the passed-in directory.
If mlflowdbfs is not used, the persisted metadata assumes that a model can be
loaded from a relative path to the metadata file (currently hard-coded to "jsl-model").
If mlflowdbfs is used, remote_model_path should be provided, and the model needs to
... | _save_model_metadata | python | mlflow/mlflow | mlflow/johnsnowlabs/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/johnsnowlabs/__init__.py | Apache-2.0 |
def _load_pyfunc(path, spark=None):
"""Load PyFunc implementation. Called by ``pyfunc.load_model``.
Args:
path: Local filesystem path to the MLflow Model with the ``johnsnowlabs`` flavor.
spark: Optionally pass spark context when using pyfunc as UDF. required, because
we cannot fetc... | Load PyFunc implementation. Called by ``pyfunc.load_model``.
Args:
path: Local filesystem path to the MLflow Model with the ``johnsnowlabs`` flavor.
spark: Optionally pass spark context when using pyfunc as UDF. required, because
we cannot fetch the Sparkcontext inside of the Workernode... | _load_pyfunc | python | mlflow/mlflow | mlflow/johnsnowlabs/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/johnsnowlabs/__init__.py | Apache-2.0 |
def _get_or_create_sparksession(model_path=None): # noqa: D417
"""Check if SparkSession running and get it.
If none exists, create a new one using jars in model_path. If model_path not defined, rely on
nlp.start() to create a new one using johnsnowlabs Jar resolution method. See
https://nlp.johnsnowla... | Check if SparkSession running and get it.
If none exists, create a new one using jars in model_path. If model_path not defined, rely on
nlp.start() to create a new one using johnsnowlabs Jar resolution method. See
https://nlp.johnsnowlabs.com/docs/en/jsl/start-a-sparksession and
https://nlp.johnsnowlab... | _get_or_create_sparksession | python | mlflow/mlflow | mlflow/johnsnowlabs/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/johnsnowlabs/__init__.py | Apache-2.0 |
def predict(self, text, params: Optional[dict[str, Any]] = None):
"""Generate predictions given input data in a pandas DataFrame.
Args:
text: pandas DataFrame containing input data.
params: Additional parameters to pass to the model for inference.
Returns:
L... | Generate predictions given input data in a pandas DataFrame.
Args:
text: pandas DataFrame containing input data.
params: Additional parameters to pass to the model for inference.
Returns:
List with model predictions.
| predict | python | mlflow/mlflow | mlflow/johnsnowlabs/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/johnsnowlabs/__init__.py | Apache-2.0 |
def _log_dataset(dataset, source, context, name=None, targets=None, model_id=None):
"""Helper function to log the dataset information to MLflow."""
try:
import tensorflow as tf
is_tf_dataset = isinstance(dataset, tf.data.Dataset)
is_tf_tensor = isinstance(dataset, tf.Tensor)
except ... | Helper function to log the dataset information to MLflow. | _log_dataset | python | mlflow/mlflow | mlflow/keras/autologging.py | https://github.com/mlflow/mlflow/blob/master/mlflow/keras/autologging.py | Apache-2.0 |
def _parse_dataset(*keras_fit_args, **keras_fit_kwargs):
"""Parse dataset from `keras.Model.fit` args and kwargs."""
x = keras_fit_kwargs["x"] if "x" in keras_fit_kwargs else keras_fit_args[0]
if "y" in keras_fit_kwargs:
# `y` is either specified as a kwarg, or the second argument to `fit`.
... | Parse dataset from `keras.Model.fit` args and kwargs. | _parse_dataset | python | mlflow/mlflow | mlflow/keras/autologging.py | https://github.com/mlflow/mlflow/blob/master/mlflow/keras/autologging.py | Apache-2.0 |
def _log_keras_model(
model,
save_exported_model,
log_model_signatures=True,
save_model_kwargs=None,
model_id=None,
):
"""Helper function to log the Keras model to MLflow."""
if log_model_signatures:
try:
signature = get_model_signature(model)
except Exception as ... | Helper function to log the Keras model to MLflow. | _log_keras_model | python | mlflow/mlflow | mlflow/keras/autologging.py | https://github.com/mlflow/mlflow/blob/master/mlflow/keras/autologging.py | Apache-2.0 |
def autolog(
log_every_epoch=True,
log_every_n_steps=None,
log_models=True,
log_model_signatures=True,
save_exported_model=False,
log_datasets=True,
log_input_examples=False,
disable=False,
exclusive=False,
disable_for_unsupported_versions=False,
silent=False,
registered_... |
Enable autologging for Keras.
This method configures the autologging for Keras workflow. Only Keras > 3 is supported. For
usage of lower Keras version (also known as tf-keras), please refer to `mlflow.tensorflow`
flavor. At a high level, calling this `mlflow.keras.autolog()` function will replace
... | autolog | python | mlflow/mlflow | mlflow/keras/autologging.py | https://github.com/mlflow/mlflow/blob/master/mlflow/keras/autologging.py | Apache-2.0 |
def on_train_begin(self, logs=None):
"""Log model architecture and optimizer configuration when training begins."""
config = self.model.optimizer.get_config()
log_params({f"optimizer_{k}": v for k, v in config.items()})
model_summary = []
def print_fn(line, *args, **kwargs):
... | Log model architecture and optimizer configuration when training begins. | on_train_begin | python | mlflow/mlflow | mlflow/keras/callback.py | https://github.com/mlflow/mlflow/blob/master/mlflow/keras/callback.py | Apache-2.0 |
def on_epoch_end(self, epoch, logs=None):
"""Log metrics at the end of each epoch."""
if not self.log_every_epoch or logs is None:
return
log_metrics(logs, step=epoch, synchronous=False, model_id=self.model_id) | Log metrics at the end of each epoch. | on_epoch_end | python | mlflow/mlflow | mlflow/keras/callback.py | https://github.com/mlflow/mlflow/blob/master/mlflow/keras/callback.py | Apache-2.0 |
def on_batch_end(self, batch, logs=None):
"""Log metrics at the end of each batch with user specified frequency."""
if self.log_every_n_steps is None or logs is None:
return
current_iteration = int(self.model.optimizer.iterations.numpy())
if current_iteration % self.log_ever... | Log metrics at the end of each batch with user specified frequency. | on_batch_end | python | mlflow/mlflow | mlflow/keras/callback.py | https://github.com/mlflow/mlflow/blob/master/mlflow/keras/callback.py | Apache-2.0 |
def on_test_end(self, logs=None):
"""Log validation metrics at validation end."""
if logs is None:
return
metrics = {"validation_" + k: v for k, v in logs.items()}
log_metrics(metrics, synchronous=False, model_id=self.model_id) | Log validation metrics at validation end. | on_test_end | python | mlflow/mlflow | mlflow/keras/callback.py | https://github.com/mlflow/mlflow/blob/master/mlflow/keras/callback.py | Apache-2.0 |
def load_model(model_uri, dst_path=None, custom_objects=None, load_model_kwargs=None):
"""
Load Keras model from MLflow.
This method loads a saved Keras model from MLflow, and returns a Keras model instance.
Args:
model_uri: The URI of the saved Keras model in MLflow. For example:
... |
Load Keras model from MLflow.
This method loads a saved Keras model from MLflow, and returns a Keras model instance.
Args:
model_uri: The URI of the saved Keras model in MLflow. For example:
- `/Users/me/path/to/local/model`
- `relative/path/to/local/model`
- ... | load_model | python | mlflow/mlflow | mlflow/keras/load.py | https://github.com/mlflow/mlflow/blob/master/mlflow/keras/load.py | Apache-2.0 |
def _load_pyfunc(path):
"""Logics of loading a saved Keras model as a PyFunc model.
This function is called by `mlflow.pyfunc.load_model`.
Args:
path: Local filesystem path to the MLflow Model with the `keras` flavor.
"""
model_meta_path1 = os.path.join(path, MLMODEL_FILE_NAME)
model_m... | Logics of loading a saved Keras model as a PyFunc model.
This function is called by `mlflow.pyfunc.load_model`.
Args:
path: Local filesystem path to the MLflow Model with the `keras` flavor.
| _load_pyfunc | python | mlflow/mlflow | mlflow/keras/load.py | https://github.com/mlflow/mlflow/blob/master/mlflow/keras/load.py | Apache-2.0 |
def save_model(
model,
path,
save_exported_model=False,
conda_env=None,
mlflow_model=None,
signature: ModelSignature = None,
input_example: ModelInputExample = None,
pip_requirements=None,
extra_pip_requirements=None,
save_model_kwargs=None,
metadata=None,
):
"""
Save... |
Save a Keras model along with metadata.
This method saves a Keras model along with metadata such as model signature and conda
environments to local file system. This method is called inside `mlflow.keras.log_model()`.
Args:
model: an instance of `keras.Model`. The Keras model to be saved.
... | save_model | python | mlflow/mlflow | mlflow/keras/save.py | https://github.com/mlflow/mlflow/blob/master/mlflow/keras/save.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.