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 predict(self, deployment_name=None, inputs=None, endpoint=None):
"""
Query a serving endpoint with the provided model inputs.
See https://docs.databricks.com/api/workspace/servingendpoints/query for request/response
schema.
Args:
deployment_name: Unused.
... |
Query a serving endpoint with the provided model inputs.
See https://docs.databricks.com/api/workspace/servingendpoints/query for request/response
schema.
Args:
deployment_name: Unused.
inputs: A dictionary containing the model inputs to query.
endpo... | predict | python | mlflow/mlflow | mlflow/deployments/databricks/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/deployments/databricks/__init__.py | Apache-2.0 |
def create_endpoint(self, name=None, config=None, route_optimized=False):
"""
Create a new serving endpoint with the provided name and configuration.
See https://docs.databricks.com/api/workspace/servingendpoints/create for request/response
schema.
Args:
name: The n... |
Create a new serving endpoint with the provided name and configuration.
See https://docs.databricks.com/api/workspace/servingendpoints/create for request/response
schema.
Args:
name: The name of the serving endpoint to create.
.. warning::
... | create_endpoint | python | mlflow/mlflow | mlflow/deployments/databricks/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/deployments/databricks/__init__.py | Apache-2.0 |
def update_endpoint_config(self, endpoint, config):
"""
Update the configuration of a specified serving endpoint. See
https://docs.databricks.com/api/workspace/servingendpoints/updateconfig for request/response
request/response schema.
Args:
endpoint: The name of the... |
Update the configuration of a specified serving endpoint. See
https://docs.databricks.com/api/workspace/servingendpoints/updateconfig for request/response
request/response schema.
Args:
endpoint: The name of the serving endpoint to update.
config: A dictionary c... | update_endpoint_config | python | mlflow/mlflow | mlflow/deployments/databricks/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/deployments/databricks/__init__.py | Apache-2.0 |
def update_endpoint_tags(self, endpoint, config):
"""
Update the tags of a specified serving endpoint. See
https://docs.databricks.com/api/workspace/servingendpoints/patch for request/response
schema.
Args:
endpoint: The name of the serving endpoint to update.
... |
Update the tags of a specified serving endpoint. See
https://docs.databricks.com/api/workspace/servingendpoints/patch for request/response
schema.
Args:
endpoint: The name of the serving endpoint to update.
config: A dictionary containing tags to add and/or remo... | update_endpoint_tags | python | mlflow/mlflow | mlflow/deployments/databricks/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/deployments/databricks/__init__.py | Apache-2.0 |
def update_endpoint_ai_gateway(self, endpoint, config):
"""
Update the AI Gateway configuration of a specified serving endpoint.
Args:
endpoint (str): The name of the serving endpoint to update.
config (dict): A dictionary containing the AI Gateway configuration to updat... |
Update the AI Gateway configuration of a specified serving endpoint.
Args:
endpoint (str): The name of the serving endpoint to update.
config (dict): A dictionary containing the AI Gateway configuration to update.
Returns:
dict: A dictionary containing the ... | update_endpoint_ai_gateway | python | mlflow/mlflow | mlflow/deployments/databricks/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/deployments/databricks/__init__.py | Apache-2.0 |
def get_endpoint(self, endpoint) -> "Endpoint":
"""
Gets a specified endpoint configured for the MLflow AI Gateway.
Args:
endpoint: The name of the endpoint to retrieve.
Returns:
An `Endpoint` object representing the endpoint.
Example:
.. code-... |
Gets a specified endpoint configured for the MLflow AI Gateway.
Args:
endpoint: The name of the endpoint to retrieve.
Returns:
An `Endpoint` object representing the endpoint.
Example:
.. code-block:: python
from mlflow.deployments import ... | get_endpoint | python | mlflow/mlflow | mlflow/deployments/mlflow/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/deployments/mlflow/__init__.py | Apache-2.0 |
def list_endpoints(self) -> "list[Endpoint]":
"""
List endpoints configured for the MLflow AI Gateway.
Returns:
A list of ``Endpoint`` objects.
Example:
.. code-block:: python
from mlflow.deployments import get_deploy_client
client = get_d... |
List endpoints configured for the MLflow AI Gateway.
Returns:
A list of ``Endpoint`` objects.
Example:
.. code-block:: python
from mlflow.deployments import get_deploy_client
client = get_deploy_client("http://localhost:5000")
endpoi... | list_endpoints | python | mlflow/mlflow | mlflow/deployments/mlflow/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/deployments/mlflow/__init__.py | Apache-2.0 |
def predict(self, deployment_name=None, inputs=None, endpoint=None):
"""Query an OpenAI endpoint.
See https://platform.openai.com/docs/api-reference for more information.
Args:
deployment_name: Unused.
inputs: A dictionary containing the model inputs to query.
... | Query an OpenAI endpoint.
See https://platform.openai.com/docs/api-reference for more information.
Args:
deployment_name: Unused.
inputs: A dictionary containing the model inputs to query.
endpoint: The name of the endpoint to query.
Returns:
A d... | predict | python | mlflow/mlflow | mlflow/deployments/openai/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/deployments/openai/__init__.py | Apache-2.0 |
def _get_api_config_without_openai_dep() -> _OpenAIApiConfig:
"""
Gets the parameters and configuration of the OpenAI API connected to.
"""
api_type = os.getenv(_OpenAIEnvVar.OPENAI_API_TYPE.value)
api_version = os.getenv(_OpenAIEnvVar.OPENAI_API_VERSION.value)
api_base = os.getenv(_OpenAIEnvVar... |
Gets the parameters and configuration of the OpenAI API connected to.
| _get_api_config_without_openai_dep | python | mlflow/mlflow | mlflow/deployments/openai/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/deployments/openai/__init__.py | Apache-2.0 |
def _load_model_fit_in_spark(local_model_path: str, flavor_conf, **kwargs):
"""
Loads a Diviner model that has been fit (and saved) in the Spark variant.
"""
# NB: To load the model DataFrame (which is a Spark DataFrame), Spark requires that the file
# partitions are in DFS. In order to facilitate t... |
Loads a Diviner model that has been fit (and saved) in the Spark variant.
| _load_model_fit_in_spark | python | mlflow/mlflow | mlflow/diviner/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/diviner/__init__.py | Apache-2.0 |
def load_model(model_uri, dst_path=None, **kwargs):
"""Load a ``Diviner`` object from a local file or a run.
Args:
model_uri: The location, in URI format, of the MLflow model. For example:
- ``/Users/me/path/to/local/model``
- ``relative/path/to/local/model``
- ``s3... | Load a ``Diviner`` object from a local file or a run.
Args:
model_uri: The location, in URI format, of the MLflow model. For example:
- ``/Users/me/path/to/local/model``
- ``relative/path/to/local/model``
- ``s3://my_bucket/path/to/model``
- ``runs:/<mlflow_... | load_model | python | mlflow/mlflow | mlflow/diviner/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/diviner/__init__.py | Apache-2.0 |
def _load_model(path, flavor_conf):
"""
Loads a Diviner model instance that was not fit using Spark from a file system location.
"""
import diviner
local_path = pathlib.Path(path)
diviner_model_path = local_path.joinpath(
flavor_conf.get(_MODEL_BINARY_KEY, _MODEL_BINARY_FILE_NAME)
... |
Loads a Diviner model instance that was not fit using Spark from a file system location.
| _load_model | python | mlflow/mlflow | mlflow/diviner/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/diviner/__init__.py | Apache-2.0 |
def autolog(
log_traces: bool = True,
log_traces_from_compile: bool = False,
log_traces_from_eval: bool = True,
log_compiles: bool = False,
log_evals: bool = False,
disable: bool = False,
silent: bool = False,
):
"""
Enables (or disables) and configures autologging from DSPy to MLflo... |
Enables (or disables) and configures autologging from DSPy to MLflow. Currently, the
MLflow DSPy flavor only supports autologging for tracing.
Args:
log_traces: If ``True``, traces are logged for DSPy models by using. If ``False``,
no traces are collected during inference. Default to `... | autolog | python | mlflow/mlflow | mlflow/dspy/autolog.py | https://github.com/mlflow/mlflow/blob/master/mlflow/dspy/autolog.py | Apache-2.0 |
def on_evaluate_start(self, call_id: str, instance: Any, inputs: dict[str, Any]):
"""
Callback handler at the beginning of evaluation call. Available with DSPy>=2.6.9.
This callback starts a nested run for each evaluation call inside optimization.
If called outside optimization and no ac... |
Callback handler at the beginning of evaluation call. Available with DSPy>=2.6.9.
This callback starts a nested run for each evaluation call inside optimization.
If called outside optimization and no active run exists, it creates a new run.
| on_evaluate_start | python | mlflow/mlflow | mlflow/dspy/callback.py | https://github.com/mlflow/mlflow/blob/master/mlflow/dspy/callback.py | Apache-2.0 |
def on_evaluate_end(
self,
call_id: str,
outputs: Any,
exception: Optional[Exception] = None,
):
"""
Callback handler at the end of evaluation call. Available with DSPy>=2.6.9.
This callback logs the evaluation score to the individual run
and add eval ... |
Callback handler at the end of evaluation call. Available with DSPy>=2.6.9.
This callback logs the evaluation score to the individual run
and add eval metric to the parent run if called inside optimization.
| on_evaluate_end | python | mlflow/mlflow | mlflow/dspy/callback.py | https://github.com/mlflow/mlflow/blob/master/mlflow/dspy/callback.py | Apache-2.0 |
def _unpack_kwargs(self, inputs: dict[str, Any]) -> dict[str, Any]:
"""Unpacks the kwargs from the inputs dictionary"""
# NB: Not using pop() to avoid modifying the original inputs dictionary
kwargs = inputs.get("kwargs", {})
inputs_wo_kwargs = {k: v for k, v in inputs.items() if k != "k... | Unpacks the kwargs from the inputs dictionary | _unpack_kwargs | python | mlflow/mlflow | mlflow/dspy/callback.py | https://github.com/mlflow/mlflow/blob/master/mlflow/dspy/callback.py | Apache-2.0 |
def _set_dependency_schema_to_tracer(model_path, callbacks):
"""
Set dependency schemas from the saved model metadata to the tracer
to propagate it to inference traces.
"""
from mlflow.dspy.callback import MlflowCallback
tracer = next((cb for cb in callbacks if isinstance(cb, MlflowCallback)), ... |
Set dependency schemas from the saved model metadata to the tracer
to propagate it to inference traces.
| _set_dependency_schema_to_tracer | python | mlflow/mlflow | mlflow/dspy/load.py | https://github.com/mlflow/mlflow/blob/master/mlflow/dspy/load.py | Apache-2.0 |
def load_model(model_uri, dst_path=None):
"""
Load a Dspy model from a run.
This function will also set the global dspy settings `dspy.settings` by the saved settings.
Args:
model_uri: The location, in URI format, of the MLflow model. For example:
- ``/Users/me/path/to/local/model... |
Load a Dspy model from a run.
This function will also set the global dspy settings `dspy.settings` by the saved settings.
Args:
model_uri: The location, in URI format, of the MLflow model. For example:
- ``/Users/me/path/to/local/model``
- ``relative/path/to/local/model``... | load_model | python | mlflow/mlflow | mlflow/dspy/load.py | https://github.com/mlflow/mlflow/blob/master/mlflow/dspy/load.py | Apache-2.0 |
def save_model(
model,
path: str,
task: Optional[str] = None,
model_config: Optional[dict[str, Any]] = None,
code_paths: Optional[list[str]] = None,
mlflow_model: Optional[Model] = None,
conda_env: Optional[Union[list[str], str]] = None,
signature: Optional[ModelSignature] = None,
in... |
Save a Dspy model.
This method saves a Dspy model along with metadata such as model signature and conda
environments to local file system. This method is called inside `mlflow.dspy.log_model()`.
Args:
model: an instance of `dspy.Module`. The Dspy model/module to be saved.
path: local ... | save_model | python | mlflow/mlflow | mlflow/dspy/save.py | https://github.com/mlflow/mlflow/blob/master/mlflow/dspy/save.py | Apache-2.0 |
def log_model(
dspy_model,
artifact_path: Optional[str] = None,
task: Optional[str] = None,
model_config: Optional[dict[str, Any]] = None,
code_paths: Optional[list[str]] = None,
conda_env: Optional[Union[list[str], str]] = None,
signature: Optional[ModelSignature] = None,
input_example:... |
Log a Dspy model along with metadata to MLflow.
This method saves a Dspy model along with metadata such as model signature and conda
environments to MLflow.
Args:
dspy_model: an instance of `dspy.Module`. The Dspy model to be saved.
artifact_path: Deprecated. Use `name` instead.
... | log_model | python | mlflow/mlflow | mlflow/dspy/save.py | https://github.com/mlflow/mlflow/blob/master/mlflow/dspy/save.py | Apache-2.0 |
def save_dspy_module_state(program, file_name: str = "model.json"):
"""
Save states of dspy `Module` to a temporary directory and log it as an artifact.
Args:
program: The dspy `Module` to be saved.
file_name: The name of the file to save the dspy module state. Default is `model.json`.
... |
Save states of dspy `Module` to a temporary directory and log it as an artifact.
Args:
program: The dspy `Module` to be saved.
file_name: The name of the file to save the dspy module state. Default is `model.json`.
| save_dspy_module_state | python | mlflow/mlflow | mlflow/dspy/util.py | https://github.com/mlflow/mlflow/blob/master/mlflow/dspy/util.py | Apache-2.0 |
def log_dspy_module_params(program):
"""
Log the parameters of the dspy `Module` as run parameters.
Args:
program: The dspy `Module` to be logged.
"""
try:
states = program.dump_state()
flat_state_dict = _flatten_dspy_module_state(
states, exclude_keys=("metadata... |
Log the parameters of the dspy `Module` as run parameters.
Args:
program: The dspy `Module` to be logged.
| log_dspy_module_params | python | mlflow/mlflow | mlflow/dspy/util.py | https://github.com/mlflow/mlflow/blob/master/mlflow/dspy/util.py | Apache-2.0 |
def log_dspy_dataset(dataset: list["Example"], file_name: str):
"""
Log the DSPy dataset as a table.
Args:
dataset: The dataset to be logged.
file_name: The name of the file to save the dataset.
"""
result = defaultdict(list)
try:
for example in dataset:
for ... |
Log the DSPy dataset as a table.
Args:
dataset: The dataset to be logged.
file_name: The name of the file to save the dataset.
| log_dspy_dataset | python | mlflow/mlflow | mlflow/dspy/util.py | https://github.com/mlflow/mlflow/blob/master/mlflow/dspy/util.py | Apache-2.0 |
def _flatten_dspy_module_state(
d, parent_key="", sep=".", exclude_keys: Optional[set] = None
) -> dict:
"""
Flattens a nested dictionary and accumulates the key names.
Args:
d: The dictionary or list to flatten.
parent_key: The base key used in recursion. Defaults to "".
sep: S... |
Flattens a nested dictionary and accumulates the key names.
Args:
d: The dictionary or list to flatten.
parent_key: The base key used in recursion. Defaults to "".
sep: Separator for nested keys. Defaults to '.'.
exclude_keys: Keys to exclude from the flattened dictionary. Defa... | _flatten_dspy_module_state | python | mlflow/mlflow | mlflow/dspy/util.py | https://github.com/mlflow/mlflow/blob/master/mlflow/dspy/util.py | Apache-2.0 |
def _get_model_input(self, inputs: Any) -> Union[str, dict[str, Any]]:
"""Convert the PythonModel input into the DSPy program input
Examples of expected conversions:
- str -> str
- dict -> dict
- np.ndarray with one element -> single element
- pd.DataFrame with one row a... | Convert the PythonModel input into the DSPy program input
Examples of expected conversions:
- str -> str
- dict -> dict
- np.ndarray with one element -> single element
- pd.DataFrame with one row and string column -> single row dict
- pd.DataFrame with one row and non-st... | _get_model_input | python | mlflow/mlflow | mlflow/dspy/wrapper.py | https://github.com/mlflow/mlflow/blob/master/mlflow/dspy/wrapper.py | Apache-2.0 |
def to_dictionary(self):
"""
Convert the Metric object to a dictionary.
Returns:
dict: The Metric object represented as a dictionary.
"""
return {
"key": self.key,
"value": self.value,
"timestamp": self.timestamp,
"step... |
Convert the Metric object to a dictionary.
Returns:
dict: The Metric object represented as a dictionary.
| to_dictionary | python | mlflow/mlflow | mlflow/entities/metric.py | https://github.com/mlflow/mlflow/blob/master/mlflow/entities/metric.py | Apache-2.0 |
def from_dictionary(cls, metric_dict):
"""
Create a Metric object from a dictionary.
Args:
metric_dict (dict): Dictionary containing metric information.
Returns:
Metric: The Metric object created from the dictionary.
"""
required_keys = ["key", "... |
Create a Metric object from a dictionary.
Args:
metric_dict (dict): Dictionary containing metric information.
Returns:
Metric: The Metric object created from the dictionary.
| from_dictionary | python | mlflow/mlflow | mlflow/entities/metric.py | https://github.com/mlflow/mlflow/blob/master/mlflow/entities/metric.py | Apache-2.0 |
def __init__(self, metrics=None, params=None, tags=None):
"""Construct a new mlflow.entities.RunData instance.
Args:
metrics: List of mlflow.entities.Metric.
params: List of mlflow.entities.Param.
tags: List of mlflow.entities.RunTag.
"""
# Maintain ... | Construct a new mlflow.entities.RunData instance.
Args:
metrics: List of mlflow.entities.Metric.
params: List of mlflow.entities.Param.
tags: List of mlflow.entities.RunTag.
| __init__ | python | mlflow/mlflow | mlflow/entities/run_data.py | https://github.com/mlflow/mlflow/blob/master/mlflow/entities/run_data.py | Apache-2.0 |
def _copy_with_overrides(self, status=None, end_time=None, lifecycle_stage=None, run_name=None):
"""A copy of the RunInfo with certain attributes modified."""
proto = self.to_proto()
if status:
proto.status = status
if end_time:
proto.end_time = end_time
i... | A copy of the RunInfo with certain attributes modified. | _copy_with_overrides | python | mlflow/mlflow | mlflow/entities/run_info.py | https://github.com/mlflow/mlflow/blob/master/mlflow/entities/run_info.py | Apache-2.0 |
def create_mlflow_span(
otel_span: Any, trace_id: str, span_type: Optional[str] = None
) -> Union["Span", "LiveSpan", "NoOpSpan"]:
"""
Factory function to create a span object.
When creating a MLflow span object from the OpenTelemetry span, the factory function
should always be used to ensure the c... |
Factory function to create a span object.
When creating a MLflow span object from the OpenTelemetry span, the factory function
should always be used to ensure the correct span object is created.
| create_mlflow_span | python | mlflow/mlflow | mlflow/entities/span.py | https://github.com/mlflow/mlflow/blob/master/mlflow/entities/span.py | Apache-2.0 |
def parent_id(self) -> Optional[str]:
"""The span ID of the parent span."""
if self._span.parent is None:
return None
return encode_span_id(self._span.parent.span_id) | The span ID of the parent span. | parent_id | python | mlflow/mlflow | mlflow/entities/span.py | https://github.com/mlflow/mlflow/blob/master/mlflow/entities/span.py | Apache-2.0 |
def events(self) -> list[SpanEvent]:
"""
Get all events of the span.
Returns:
A list of all events of the span.
"""
return [
SpanEvent(
name=event.name,
timestamp=event.timestamp,
# Convert from OpenTelemetr... |
Get all events of the span.
Returns:
A list of all events of the span.
| events | python | mlflow/mlflow | mlflow/entities/span.py | https://github.com/mlflow/mlflow/blob/master/mlflow/entities/span.py | Apache-2.0 |
def from_dict(cls, data: dict[str, Any]) -> "Span":
"""Create a Span object from the given dictionary."""
try:
# Try to deserialize the span using the v3 schema
request_id = data.get("attributes", {}).get(SpanAttributeKey.REQUEST_ID)
if not request_id:
... | Create a Span object from the given dictionary. | from_dict | python | mlflow/mlflow | mlflow/entities/span.py | https://github.com/mlflow/mlflow/blob/master/mlflow/entities/span.py | Apache-2.0 |
def from_dict_v2(cls, data: dict[str, Any]) -> "Span":
"""Create a Span object from the given dictionary in v2 schema."""
trace_id = decode_id(data["context"]["trace_id"])
span_id = decode_id(data["context"]["span_id"])
parent_id = decode_id(data["parent_id"]) if data["parent_id"] else N... | Create a Span object from the given dictionary in v2 schema. | from_dict_v2 | python | mlflow/mlflow | mlflow/entities/span.py | https://github.com/mlflow/mlflow/blob/master/mlflow/entities/span.py | Apache-2.0 |
def to_proto(self):
"""Convert into OTLP compatible proto object to sent to the Databricks Trace Server."""
otel_status = self._span.status
status = ProtoSpan.Status(
code=otel_status.status_code.value,
message=otel_status.description,
)
parent = _encode_s... | Convert into OTLP compatible proto object to sent to the Databricks Trace Server. | to_proto | python | mlflow/mlflow | mlflow/entities/span.py | https://github.com/mlflow/mlflow/blob/master/mlflow/entities/span.py | Apache-2.0 |
def __init__(
self,
otel_span: OTelSpan,
trace_id: str,
span_type: str = SpanType.UNKNOWN,
):
"""
The `otel_span` argument takes an instance of OpenTelemetry Span class, which is
indeed a subclass of ReadableSpan. Thanks to this, the getter methods of the Span... |
The `otel_span` argument takes an instance of OpenTelemetry Span class, which is
indeed a subclass of ReadableSpan. Thanks to this, the getter methods of the Span
class can be reused without any modification.
Note that the constructor doesn't call the super().__init__ method, because t... | __init__ | python | mlflow/mlflow | mlflow/entities/span.py | https://github.com/mlflow/mlflow/blob/master/mlflow/entities/span.py | Apache-2.0 |
def set_attributes(self, attributes: dict[str, Any]):
"""
Set the attributes to the span. The attributes must be a dictionary of key-value pairs.
This method is additive, i.e. it will add new attributes to the existing ones. If an
attribute with the same key already exists, it will be ov... |
Set the attributes to the span. The attributes must be a dictionary of key-value pairs.
This method is additive, i.e. it will add new attributes to the existing ones. If an
attribute with the same key already exists, it will be overwritten.
| set_attributes | python | mlflow/mlflow | mlflow/entities/span.py | https://github.com/mlflow/mlflow/blob/master/mlflow/entities/span.py | Apache-2.0 |
def set_status(self, status: Union[SpanStatusCode, str]):
"""
Set the status of the span.
Args:
status: The status of the span. This can be a
:py:class:`SpanStatus <mlflow.entities.SpanStatus>` object or a string representing
of the status code define... |
Set the status of the span.
Args:
status: The status of the span. This can be a
:py:class:`SpanStatus <mlflow.entities.SpanStatus>` object or a string representing
of the status code defined in
:py:class:`SpanStatusCode <mlflow.entities.SpanS... | set_status | python | mlflow/mlflow | mlflow/entities/span.py | https://github.com/mlflow/mlflow/blob/master/mlflow/entities/span.py | Apache-2.0 |
def record_exception(self, exception: Union[str, Exception]):
"""
Record an exception on the span, adding an exception event and setting span status to ERROR.
Args:
exception: The exception to record. Can be an Exception instance or a string
describing the exception.... |
Record an exception on the span, adding an exception event and setting span status to ERROR.
Args:
exception: The exception to record. Can be an Exception instance or a string
describing the exception.
| record_exception | python | mlflow/mlflow | mlflow/entities/span.py | https://github.com/mlflow/mlflow/blob/master/mlflow/entities/span.py | Apache-2.0 |
def end(
self,
outputs: Optional[Any] = None,
attributes: Optional[dict[str, Any]] = None,
status: Optional[Union[SpanStatus, str]] = None,
end_time_ns: Optional[int] = None,
):
"""
End the span.
outputs: Outputs to set on the span.
attributes... |
End the span.
outputs: Outputs to set on the span.
attributes: A dictionary of attributes to set on the span. If the span already has
attributes, the new attributes will be merged with the existing ones. If the same
key already exists, the new value will overwrite the o... | end | python | mlflow/mlflow | mlflow/entities/span.py | https://github.com/mlflow/mlflow/blob/master/mlflow/entities/span.py | Apache-2.0 |
def from_immutable_span(
cls,
span: Span,
parent_span_id: Optional[str] = None,
trace_id: Optional[str] = None,
otel_trace_id: Optional[str] = None,
end_trace: bool = True,
) -> "LiveSpan":
"""
Create a new LiveSpan object from the given immutable span... |
Create a new LiveSpan object from the given immutable span by
cloning the underlying OpenTelemetry span within current context.
This is particularly useful when we merging a remote trace into the current trace.
We cannot merge the remote trace directly, because it is already stored as ... | from_immutable_span | python | mlflow/mlflow | mlflow/entities/span.py | https://github.com/mlflow/mlflow/blob/master/mlflow/entities/span.py | Apache-2.0 |
def from_exception(cls, exception: Exception):
"Create a span event from an exception."
stack_trace = cls._get_stacktrace(exception)
return cls(
name="exception",
attributes={
"exception.message": str(exception),
"exception.type": exceptio... | Create a span event from an exception. | from_exception | python | mlflow/mlflow | mlflow/entities/span_event.py | https://github.com/mlflow/mlflow/blob/master/mlflow/entities/span_event.py | Apache-2.0 |
def _get_stacktrace(error: BaseException) -> str:
"""Get the stacktrace of the parent error."""
msg = repr(error)
try:
if sys.version_info < (3, 10):
tb = traceback.format_exception(error.__class__, error, error.__traceback__)
else:
tb = tr... | Get the stacktrace of the parent error. | _get_stacktrace | python | mlflow/mlflow | mlflow/entities/span_event.py | https://github.com/mlflow/mlflow/blob/master/mlflow/entities/span_event.py | Apache-2.0 |
def from_proto_status_code(status_code: str) -> SpanStatusCode:
"""
Convert a string status code to the corresponding SpanStatusCode enum value.
"""
from mlflow.protos.databricks_trace_server_pb2 import Span as ProtoSpan
proto_code = ProtoSpan.Status.StatusCode
status_co... |
Convert a string status code to the corresponding SpanStatusCode enum value.
| from_proto_status_code | python | mlflow/mlflow | mlflow/entities/span_status.py | https://github.com/mlflow/mlflow/blob/master/mlflow/entities/span_status.py | Apache-2.0 |
def __post_init__(self):
"""
If user provides a string status code, validate it and convert to
the corresponding enum value.
"""
if isinstance(self.status_code, str):
try:
self.status_code = SpanStatusCode(self.status_code)
except ValueErro... |
If user provides a string status code, validate it and convert to
the corresponding enum value.
| __post_init__ | python | mlflow/mlflow | mlflow/entities/span_status.py | https://github.com/mlflow/mlflow/blob/master/mlflow/entities/span_status.py | Apache-2.0 |
def to_otel_status(self) -> trace_api.Status:
"""
Convert :py:class:`mlflow.entities.SpanStatus` object to OpenTelemetry status object.
:meta private:
"""
try:
status_code = getattr(trace_api.StatusCode, self.status_code.name)
except AttributeError:
... |
Convert :py:class:`mlflow.entities.SpanStatus` object to OpenTelemetry status object.
:meta private:
| to_otel_status | python | mlflow/mlflow | mlflow/entities/span_status.py | https://github.com/mlflow/mlflow/blob/master/mlflow/entities/span_status.py | Apache-2.0 |
def from_otel_status(cls, otel_status: trace_api.Status) -> SpanStatus:
"""
Convert OpenTelemetry status object to our status object.
:meta private:
"""
try:
status_code = SpanStatusCode(otel_status.status_code.name)
except ValueError:
raise Mlflo... |
Convert OpenTelemetry status object to our status object.
:meta private:
| from_otel_status | python | mlflow/mlflow | mlflow/entities/span_status.py | https://github.com/mlflow/mlflow/blob/master/mlflow/entities/span_status.py | Apache-2.0 |
def _repr_mimebundle_(self, include=None, exclude=None):
"""
This method is used to trigger custom display logic in IPython notebooks.
See https://ipython.readthedocs.io/en/stable/config/integrating.html#MyObject
for more details.
At the moment, the only supported MIME type is "... |
This method is used to trigger custom display logic in IPython notebooks.
See https://ipython.readthedocs.io/en/stable/config/integrating.html#MyObject
for more details.
At the moment, the only supported MIME type is "application/databricks.mlflow.trace",
which contains a JSON ... | _repr_mimebundle_ | python | mlflow/mlflow | mlflow/entities/trace.py | https://github.com/mlflow/mlflow/blob/master/mlflow/entities/trace.py | Apache-2.0 |
def search_spans(
self,
span_type: Optional[SpanType] = None,
name: Optional[Union[str, re.Pattern]] = None,
span_id: Optional[str] = None,
) -> list[Span]:
"""
Search for spans that match the given criteria within the trace.
Args:
span_type: The ... |
Search for spans that match the given criteria within the trace.
Args:
span_type: The type of the span to search for.
name: The name of the span to search for. This can be a string or a regular expression.
span_id: The ID of the span to search for.
Returns:... | search_spans | python | mlflow/mlflow | mlflow/entities/trace.py | https://github.com/mlflow/mlflow/blob/master/mlflow/entities/trace.py | Apache-2.0 |
def search_assessments(
self,
name: Optional[str] = None,
*,
span_id: Optional[str] = None,
all: bool = False,
type: Optional[Literal["expectation", "feedback"]] = None,
) -> list["Assessment"]:
"""
Get assessments for a given name / span ID. By defaul... |
Get assessments for a given name / span ID. By default, this only returns assessments
that are valid (i.e. have not been overridden by another assessment). To return all
assessments, specify `all=True`.
Args:
name: The name of the assessment to get. If not provided, this wi... | search_assessments | python | mlflow/mlflow | mlflow/entities/trace.py | https://github.com/mlflow/mlflow/blob/master/mlflow/entities/trace.py | Apache-2.0 |
def intermediate_outputs(self) -> Optional[dict[str, Any]]:
"""
Returns intermediate outputs produced by the model or agent while handling the request.
There are mainly two flows to return intermediate outputs:
1. When a trace is generate by the `mlflow.log_trace` API,
return `in... |
Returns intermediate outputs produced by the model or agent while handling the request.
There are mainly two flows to return intermediate outputs:
1. When a trace is generate by the `mlflow.log_trace` API,
return `intermediate_outputs` attribute of the span.
2. When a trace is c... | intermediate_outputs | python | mlflow/mlflow | mlflow/entities/trace_data.py | https://github.com/mlflow/mlflow/blob/master/mlflow/entities/trace_data.py | Apache-2.0 |
def experiment_id(self) -> Optional[str]:
"""
An MLflow experiment ID associated with the trace, if the trace is stored
in MLflow tracking server. Otherwise, None.
"""
return (
self.trace_location.mlflow_experiment
and self.trace_location.mlflow_experiment... |
An MLflow experiment ID associated with the trace, if the trace is stored
in MLflow tracking server. Otherwise, None.
| experiment_id | python | mlflow/mlflow | mlflow/entities/trace_info.py | https://github.com/mlflow/mlflow/blob/master/mlflow/entities/trace_info.py | Apache-2.0 |
def token_usage(self) -> Optional[dict[str, int]]:
"""
Returns the aggregated token usage for the trace.
Returns:
A dictionary containing the aggregated LLM token usage for the trace.
- "input_tokens": The total number of input tokens.
- "output_tokens": The ... |
Returns the aggregated token usage for the trace.
Returns:
A dictionary containing the aggregated LLM token usage for the trace.
- "input_tokens": The total number of input tokens.
- "output_tokens": The total number of output tokens.
- "total_tokens": S... | token_usage | python | mlflow/mlflow | mlflow/entities/trace_info.py | https://github.com/mlflow/mlflow/blob/master/mlflow/entities/trace_info.py | Apache-2.0 |
def to_dict(self):
"""
Convert trace info to a dictionary for persistence.
Update status field to the string value for serialization.
"""
trace_info_dict = asdict(self)
trace_info_dict["status"] = self.status.value
# Client request ID field is only added for inter... |
Convert trace info to a dictionary for persistence.
Update status field to the string value for serialization.
| to_dict | python | mlflow/mlflow | mlflow/entities/trace_info_v2.py | https://github.com/mlflow/mlflow/blob/master/mlflow/entities/trace_info_v2.py | Apache-2.0 |
def from_dict(cls, trace_info_dict):
"""
Convert trace info dictionary to TraceInfo object.
"""
if "status" not in trace_info_dict:
raise ValueError("status is required in trace info dictionary.")
trace_info_dict["status"] = TraceStatus(trace_info_dict["status"])
... |
Convert trace info dictionary to TraceInfo object.
| from_dict | python | mlflow/mlflow | mlflow/entities/trace_info_v2.py | https://github.com/mlflow/mlflow/blob/master/mlflow/entities/trace_info_v2.py | Apache-2.0 |
def __init__(
self,
name: str,
description: Optional[str] = None,
creation_timestamp: Optional[int] = None,
tags: Optional[dict[str, str]] = None,
):
"""
Construct a Prompt entity.
Args:
name: Name of the prompt.
description: D... |
Construct a Prompt entity.
Args:
name: Name of the prompt.
description: Description of the prompt.
creation_timestamp: Timestamp when the prompt was created.
tags: Prompt-level metadata as key-value pairs.
| __init__ | python | mlflow/mlflow | mlflow/entities/model_registry/prompt.py | https://github.com/mlflow/mlflow/blob/master/mlflow/entities/model_registry/prompt.py | Apache-2.0 |
def to_single_brace_format(self) -> str:
"""
Convert the template text to single brace format. This is useful for integrating with other
systems that use single curly braces for variable replacement, such as LangChain's prompt
template. Default is False.
"""
t = self.temp... |
Convert the template text to single brace format. This is useful for integrating with other
systems that use single curly braces for variable replacement, such as LangChain's prompt
template. Default is False.
| to_single_brace_format | python | mlflow/mlflow | mlflow/entities/model_registry/prompt_version.py | https://github.com/mlflow/mlflow/blob/master/mlflow/entities/model_registry/prompt_version.py | Apache-2.0 |
def format(self, allow_partial: bool = False, **kwargs) -> Union[PromptVersion, str]:
"""
Format the template text with the given keyword arguments.
By default, it raises an error if there are missing variables. To format
the prompt text partially, set `allow_partial=True`.
Exam... |
Format the template text with the given keyword arguments.
By default, it raises an error if there are missing variables. To format
the prompt text partially, set `allow_partial=True`.
Example:
.. code-block:: python
prompt = Prompt("my-prompt", 1, "Hello, {{title... | format | python | mlflow/mlflow | mlflow/entities/model_registry/prompt_version.py | https://github.com/mlflow/mlflow/blob/master/mlflow/entities/model_registry/prompt_version.py | Apache-2.0 |
def tags(self):
"""Dictionary of tag key (string) -> tag value for the current registered model."""
# Remove the is_prompt tag as it should not be user-facing
return {k: v for k, v in self._tags.items() if k != IS_PROMPT_TAG_KEY} | Dictionary of tag key (string) -> tag value for the current registered model. | tags | python | mlflow/mlflow | mlflow/entities/model_registry/registered_model.py | https://github.com/mlflow/mlflow/blob/master/mlflow/entities/model_registry/registered_model.py | Apache-2.0 |
def __init__(
self,
evaluation_id: str,
name: str,
source: AssessmentSource,
timestamp: int,
boolean_value: Optional[bool] = None,
numeric_value: Optional[float] = None,
string_value: Optional[str] = None,
rationale: Optional[str] = None,
m... | Construct a new mlflow.evaluation.AssessmentEntity instance.
Args:
evaluation_id: The ID of the evaluation with which the assessment is associated.
name: The name of the assessment.
source: The source of the assessment (AssessmentSource instance).
timestamp: The ... | __init__ | python | mlflow/mlflow | mlflow/evaluation/assessment.py | https://github.com/mlflow/mlflow/blob/master/mlflow/evaluation/assessment.py | Apache-2.0 |
def from_dictionary(cls, assessment_dict: dict[str, Any]) -> "AssessmentEntity":
"""
Create an Assessment object from a dictionary.
Args:
assessment_dict (dict): Dictionary containing assessment information.
Returns:
Assessment: The Assessment object created fro... |
Create an Assessment object from a dictionary.
Args:
assessment_dict (dict): Dictionary containing assessment information.
Returns:
Assessment: The Assessment object created from the dictionary.
| from_dictionary | python | mlflow/mlflow | mlflow/evaluation/assessment.py | https://github.com/mlflow/mlflow/blob/master/mlflow/evaluation/assessment.py | Apache-2.0 |
def __init__(
self,
name: str,
source: Optional[AssessmentSource] = None,
value: Optional[Union[bool, float, str]] = None,
rationale: Optional[str] = None,
metadata: Optional[dict[str, Any]] = None,
error_code: Optional[str] = None,
error_message: Optional... | Construct a new Assessment instance.
Args:
name: The name of the piece of assessment.
source: The source of the assessment (AssessmentSource instance).
value: The value of the assessment. This can be a boolean, numeric, or string value.
rationale: The rationale /... | __init__ | python | mlflow/mlflow | mlflow/evaluation/assessment.py | https://github.com/mlflow/mlflow/blob/master/mlflow/evaluation/assessment.py | Apache-2.0 |
def __init__(
self,
evaluation_id: str,
run_id: str,
inputs_id: str,
inputs: dict[str, Any],
outputs: Optional[dict[str, Any]] = None,
request_id: Optional[str] = None,
targets: Optional[dict[str, Any]] = None,
error_code: Optional[str] = None,
... |
Construct a new mlflow.evaluation.EvaluationEntity instance.
Args:
evaluation_id: A unique identifier for the evaluation.
run_id: The ID of the MLflow Run containing the Evaluation.
inputs_id: A unique identifier for the input names and values for evaluation.
... | __init__ | python | mlflow/mlflow | mlflow/evaluation/evaluation.py | https://github.com/mlflow/mlflow/blob/master/mlflow/evaluation/evaluation.py | Apache-2.0 |
def to_dictionary(self) -> dict[str, Any]:
"""
Convert the Evaluation object to a dictionary.
Returns:
dict: The Evaluation object represented as a dictionary.
"""
evaluation_dict = {
"evaluation_id": self.evaluation_id,
"run_id": self.run_id,... |
Convert the Evaluation object to a dictionary.
Returns:
dict: The Evaluation object represented as a dictionary.
| to_dictionary | python | mlflow/mlflow | mlflow/evaluation/evaluation.py | https://github.com/mlflow/mlflow/blob/master/mlflow/evaluation/evaluation.py | Apache-2.0 |
def from_dictionary(cls, evaluation_dict: dict[str, Any]):
"""
Create an Evaluation object from a dictionary.
Args:
evaluation_dict (dict): Dictionary containing evaluation information.
Returns:
Evaluation: The Evaluation object created from the dictionary.
... |
Create an Evaluation object from a dictionary.
Args:
evaluation_dict (dict): Dictionary containing evaluation information.
Returns:
Evaluation: The Evaluation object created from the dictionary.
| from_dictionary | python | mlflow/mlflow | mlflow/evaluation/evaluation.py | https://github.com/mlflow/mlflow/blob/master/mlflow/evaluation/evaluation.py | Apache-2.0 |
def __init__(
self,
inputs: dict[str, Any],
outputs: Optional[dict[str, Any]] = None,
inputs_id: Optional[str] = None,
request_id: Optional[str] = None,
targets: Optional[dict[str, Any]] = None,
error_code: Optional[str] = None,
error_message: Optional[str... |
Construct a new Evaluation instance.
Args:
inputs: Input names and values for evaluation.
outputs: Outputs obtained during inference.
inputs_id: A unique identifier for the input names and values for evaluation.
request_id: The ID of an MLflow Trace corr... | __init__ | python | mlflow/mlflow | mlflow/evaluation/evaluation.py | https://github.com/mlflow/mlflow/blob/master/mlflow/evaluation/evaluation.py | Apache-2.0 |
def _to_entity(self, run_id: str, evaluation_id: str) -> EvaluationEntity:
"""
Convert the Evaluation object to an EvaluationEntity object.
Returns:
EvaluationEntity: An EvaluationEntity object.
"""
return EvaluationEntity(
evaluation_id=evaluation_id,
... |
Convert the Evaluation object to an EvaluationEntity object.
Returns:
EvaluationEntity: An EvaluationEntity object.
| _to_entity | python | mlflow/mlflow | mlflow/evaluation/evaluation.py | https://github.com/mlflow/mlflow/blob/master/mlflow/evaluation/evaluation.py | Apache-2.0 |
def to_dictionary(self) -> dict[str, str]:
"""
Convert the EvaluationTag object to a dictionary.
Returns:
dict: The EvaluationTag object represented as a dictionary.
"""
return {
"key": self.key,
"value": self.value,
} |
Convert the EvaluationTag object to a dictionary.
Returns:
dict: The EvaluationTag object represented as a dictionary.
| to_dictionary | python | mlflow/mlflow | mlflow/evaluation/evaluation_tag.py | https://github.com/mlflow/mlflow/blob/master/mlflow/evaluation/evaluation_tag.py | Apache-2.0 |
def from_dictionary(cls, evaluation_tag_dict: dict[str, str]):
"""
Create an EvaluationTag object from a dictionary.
Args:
evaluation_tag_dict (dict): Dictionary containing evaluation tag information.
Returns:
Evaluation: The EvaluationTag object created from th... |
Create an EvaluationTag object from a dictionary.
Args:
evaluation_tag_dict (dict): Dictionary containing evaluation tag information.
Returns:
Evaluation: The EvaluationTag object created from the dictionary.
| from_dictionary | python | mlflow/mlflow | mlflow/evaluation/evaluation_tag.py | https://github.com/mlflow/mlflow/blob/master/mlflow/evaluation/evaluation_tag.py | Apache-2.0 |
def log_evaluations(
*, evaluations: list[Evaluation], run_id: Optional[str] = None
) -> list[EvaluationEntity]:
"""
Logs one or more evaluations to an MLflow Run.
Args:
evaluations (List[Evaluation]): List of one or more MLflow Evaluation objects.
run_id (Optional[str]): ID of the MLflow R... |
Logs one or more evaluations to an MLflow Run.
Args:
evaluations (List[Evaluation]): List of one or more MLflow Evaluation objects.
run_id (Optional[str]): ID of the MLflow Run to log the evaluation. If unspecified, the
current active run is used, or a new run is started.
Returns:
... | log_evaluations | python | mlflow/mlflow | mlflow/evaluation/fluent.py | https://github.com/mlflow/mlflow/blob/master/mlflow/evaluation/fluent.py | Apache-2.0 |
def evaluations_to_dataframes(
evaluations: list[EvaluationEntity],
) -> tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame, pd.DataFrame]:
"""
Converts a list of Evaluation entities to four separate DataFrames: one for main evaluation
data (excluding assessments and metrics), one for metrics, one for asses... |
Converts a list of Evaluation entities to four separate DataFrames: one for main evaluation
data (excluding assessments and metrics), one for metrics, one for assessments, and one for
tags.
Args:
evaluations (List[Evaluation]): List of Evaluation entities.
Returns:
Tuple[pd.DataFr... | evaluations_to_dataframes | python | mlflow/mlflow | mlflow/evaluation/utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/evaluation/utils.py | Apache-2.0 |
def _get_evaluations_dataframe_schema() -> dict[str, str]:
"""
Returns the pandas schema for the evaluation DataFrame.
"""
return {
"evaluation_id": "string",
"run_id": "string",
"inputs_id": "string",
"inputs": "object",
"outputs": "object",
"request_id":... |
Returns the pandas schema for the evaluation DataFrame.
| _get_evaluations_dataframe_schema | python | mlflow/mlflow | mlflow/evaluation/utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/evaluation/utils.py | Apache-2.0 |
def _get_empty_evaluations_dataframe() -> pd.DataFrame:
"""
Creates an empty DataFrame with columns for evaluation data.
"""
schema = _get_evaluations_dataframe_schema()
df = pd.DataFrame(columns=schema.keys())
return _apply_schema_to_dataframe(df, schema) |
Creates an empty DataFrame with columns for evaluation data.
| _get_empty_evaluations_dataframe | python | mlflow/mlflow | mlflow/evaluation/utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/evaluation/utils.py | Apache-2.0 |
def _get_assessments_dataframe_schema() -> dict[str, str]:
"""
Returns the pandas schema for the assessments DataFrame.
"""
return {
"evaluation_id": "string",
"name": "string",
"source": "object",
"timestamp": "int64",
"boolean_value": "object",
"numeric_... |
Returns the pandas schema for the assessments DataFrame.
| _get_assessments_dataframe_schema | python | mlflow/mlflow | mlflow/evaluation/utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/evaluation/utils.py | Apache-2.0 |
def _get_empty_assessments_dataframe() -> pd.DataFrame:
"""
Creates an empty DataFrame with columns for evaluation assessments data.
"""
schema = _get_assessments_dataframe_schema()
df = pd.DataFrame(columns=schema.keys())
return _apply_schema_to_dataframe(df, schema) |
Creates an empty DataFrame with columns for evaluation assessments data.
| _get_empty_assessments_dataframe | python | mlflow/mlflow | mlflow/evaluation/utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/evaluation/utils.py | Apache-2.0 |
def _get_metrics_dataframe_schema() -> dict[str, str]:
"""
Returns the pandas schema for the metrics DataFrame.
"""
return {
"evaluation_id": "string",
"key": "string",
"value": "float64",
"timestamp": "int64",
"model_id": "string",
"dataset_name": "string... |
Returns the pandas schema for the metrics DataFrame.
| _get_metrics_dataframe_schema | python | mlflow/mlflow | mlflow/evaluation/utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/evaluation/utils.py | Apache-2.0 |
def _get_empty_metrics_dataframe() -> pd.DataFrame:
"""
Creates an empty DataFrame with columns for evaluation metric data.
"""
schema = _get_metrics_dataframe_schema()
df = pd.DataFrame(columns=schema.keys())
return _apply_schema_to_dataframe(df, schema) |
Creates an empty DataFrame with columns for evaluation metric data.
| _get_empty_metrics_dataframe | python | mlflow/mlflow | mlflow/evaluation/utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/evaluation/utils.py | Apache-2.0 |
def _get_tags_dataframe_schema() -> dict[str, str]:
"""
Returns the pandas schema for the tags DataFrame.
"""
return {
"evaluation_id": "string",
"key": "string",
"value": "string",
} |
Returns the pandas schema for the tags DataFrame.
| _get_tags_dataframe_schema | python | mlflow/mlflow | mlflow/evaluation/utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/evaluation/utils.py | Apache-2.0 |
def _get_empty_tags_dataframe() -> pd.DataFrame:
"""
Creates an empty DataFrame with columns for evaluation tags data.
"""
schema = _get_tags_dataframe_schema()
df = pd.DataFrame(columns=schema.keys())
return _apply_schema_to_dataframe(df, schema) |
Creates an empty DataFrame with columns for evaluation tags data.
| _get_empty_tags_dataframe | python | mlflow/mlflow | mlflow/evaluation/utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/evaluation/utils.py | Apache-2.0 |
def _apply_schema_to_dataframe(df: pd.DataFrame, schema: dict[str, str]) -> pd.DataFrame:
"""
Applies a schema to a DataFrame.
Args:
df (pd.DataFrame): DataFrame to apply the schema to.
schema (Dict[str, Any]): Schema to apply.
Returns:
pd.DataFrame: DataFrame with schema appli... |
Applies a schema to a DataFrame.
Args:
df (pd.DataFrame): DataFrame to apply the schema to.
schema (Dict[str, Any]): Schema to apply.
Returns:
pd.DataFrame: DataFrame with schema applied.
| _apply_schema_to_dataframe | python | mlflow/mlflow | mlflow/evaluation/utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/evaluation/utils.py | Apache-2.0 |
def _translate_http_exception(func):
"""
Decorator for translating MLflow exceptions to HTTP exceptions
"""
@functools.wraps(func)
async def wrapper(*args, **kwargs):
try:
return await func(*args, **kwargs)
except AIGatewayException as e:
raise HTTPException(... |
Decorator for translating MLflow exceptions to HTTP exceptions
| _translate_http_exception | python | mlflow/mlflow | mlflow/gateway/app.py | https://github.com/mlflow/mlflow/blob/master/mlflow/gateway/app.py | Apache-2.0 |
def create_app_from_config(config: GatewayConfig) -> GatewayAPI:
"""
Create the GatewayAPI app from the gateway configuration.
"""
limiter = Limiter(
key_func=get_remote_address, storage_uri=MLFLOW_GATEWAY_RATE_LIMITS_STORAGE_URI.get()
)
app = GatewayAPI(
config=config,
l... |
Create the GatewayAPI app from the gateway configuration.
| create_app_from_config | python | mlflow/mlflow | mlflow/gateway/app.py | https://github.com/mlflow/mlflow/blob/master/mlflow/gateway/app.py | Apache-2.0 |
def create_app_from_env() -> GatewayAPI:
"""
Load the path from the environment variable and generate the GatewayAPI app instance.
"""
if config_path := MLFLOW_GATEWAY_CONFIG.get():
return create_app_from_path(config_path)
raise MlflowException(
f"Environment variable {MLFLOW_GATEWA... |
Load the path from the environment variable and generate the GatewayAPI app instance.
| create_app_from_env | python | mlflow/mlflow | mlflow/gateway/app.py | https://github.com/mlflow/mlflow/blob/master/mlflow/gateway/app.py | Apache-2.0 |
def _missing_(cls, value):
"""
Implements case-insensitive matching of API type strings
"""
for api_type in cls:
if api_type.value == value.lower():
return api_type
raise MlflowException.invalid_parameter_value(f"Invalid OpenAI API type '{value}'") |
Implements case-insensitive matching of API type strings
| _missing_ | python | mlflow/mlflow | mlflow/gateway/config.py | https://github.com/mlflow/mlflow/blob/master/mlflow/gateway/config.py | Apache-2.0 |
def _resolve_api_key_from_input(api_key_input):
"""
Resolves the provided API key.
Input formats accepted:
- Path to a file as a string which will have the key loaded from it
- environment variable name that stores the api key
- the api key itself
"""
if not isinstance(api_key_input, ... |
Resolves the provided API key.
Input formats accepted:
- Path to a file as a string which will have the key loaded from it
- environment variable name that stores the api key
- the api key itself
| _resolve_api_key_from_input | python | mlflow/mlflow | mlflow/gateway/config.py | https://github.com/mlflow/mlflow/blob/master/mlflow/gateway/config.py | Apache-2.0 |
def _load_route_config(path: Union[str, Path]) -> GatewayConfig:
"""
Reads the gateway configuration yaml file from the storage location and returns an instance
of the configuration RouteConfig class
"""
if isinstance(path, str):
path = Path(path)
try:
configuration = yaml.safe_l... |
Reads the gateway configuration yaml file from the storage location and returns an instance
of the configuration RouteConfig class
| _load_route_config | python | mlflow/mlflow | mlflow/gateway/config.py | https://github.com/mlflow/mlflow/blob/master/mlflow/gateway/config.py | Apache-2.0 |
def uc_type_to_json_schema_type(uc_type_json: Union[str, dict[str, Any]]) -> dict[str, Any]:
"""
Converts the JSON representation of a Unity Catalog data type to the corresponding JSON schema
type. The conversion is lossy because we do not need to convert it back.
"""
# See https://docs.databricks.c... |
Converts the JSON representation of a Unity Catalog data type to the corresponding JSON schema
type. The conversion is lossy because we do not need to convert it back.
| uc_type_to_json_schema_type | python | mlflow/mlflow | mlflow/gateway/uc_function_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/gateway/uc_function_utils.py | Apache-2.0 |
def is_scalar(function: "FunctionInfo") -> bool:
"""
Returns True if the function returns a single row instead of a table.
"""
from databricks.sdk.service.catalog import ColumnTypeName
return function.data_type != ColumnTypeName.TABLE_TYPE |
Returns True if the function returns a single row instead of a table.
| is_scalar | python | mlflow/mlflow | mlflow/gateway/uc_function_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/gateway/uc_function_utils.py | Apache-2.0 |
def execute_function(
ws: "WorkspaceClient",
warehouse_id: str,
function: "FunctionInfo",
parameters: dict[str, Any],
) -> FunctionExecutionResult:
"""
Execute a function with the given arguments and return the result.
"""
try:
import pandas as pd
except ImportError as e:
... |
Execute a function with the given arguments and return the result.
| execute_function | python | mlflow/mlflow | mlflow/gateway/uc_function_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/gateway/uc_function_utils.py | Apache-2.0 |
def kill_child_processes(parent_pid):
"""
Gracefully terminate or kill child processes from a main process
"""
import psutil
parent = psutil.Process(parent_pid)
for child in parent.children(recursive=True):
try:
child.terminate()
except psutil.NoSuchProcess:
... |
Gracefully terminate or kill child processes from a main process
| kill_child_processes | python | mlflow/mlflow | mlflow/gateway/utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/gateway/utils.py | Apache-2.0 |
def _is_valid_uri(uri: str):
"""
Evaluates the basic structure of a provided gateway uri to determine if the scheme and
netloc are provided
"""
if uri == "databricks":
return True
try:
parsed = urlparse(uri)
return parsed.scheme == "databricks" or all([parsed.scheme, pars... |
Evaluates the basic structure of a provided gateway uri to determine if the scheme and
netloc are provided
| _is_valid_uri | python | mlflow/mlflow | mlflow/gateway/utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/gateway/utils.py | Apache-2.0 |
def set_gateway_uri(gateway_uri: str):
"""Sets the uri of a configured and running MLflow AI Gateway server in a global context.
Providing a valid uri and calling this function is required in order to use the MLflow
AI Gateway fluent APIs.
Args:
gateway_uri: The full uri of a running MLflow AI ... | Sets the uri of a configured and running MLflow AI Gateway server in a global context.
Providing a valid uri and calling this function is required in order to use the MLflow
AI Gateway fluent APIs.
Args:
gateway_uri: The full uri of a running MLflow AI Gateway server or, if running on
D... | set_gateway_uri | python | mlflow/mlflow | mlflow/gateway/utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/gateway/utils.py | Apache-2.0 |
def get_gateway_uri() -> str:
"""
Returns the currently set MLflow AI Gateway server uri iff set.
If the Gateway uri has not been set by using ``set_gateway_uri``, an ``MlflowException``
is raised.
"""
if _gateway_uri is not None:
return _gateway_uri
elif uri := MLFLOW_GATEWAY_URI.ge... |
Returns the currently set MLflow AI Gateway server uri iff set.
If the Gateway uri has not been set by using ``set_gateway_uri``, an ``MlflowException``
is raised.
| get_gateway_uri | python | mlflow/mlflow | mlflow/gateway/utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/gateway/utils.py | Apache-2.0 |
def assemble_uri_path(paths: list[str]) -> str:
"""Assemble a correct URI path from a list of path parts.
Args:
paths: A list of strings representing parts of a URI path.
Returns:
A string representing the complete assembled URI path.
"""
stripped_paths = [path.strip("/").lstrip("... | Assemble a correct URI path from a list of path parts.
Args:
paths: A list of strings representing parts of a URI path.
Returns:
A string representing the complete assembled URI path.
| assemble_uri_path | python | mlflow/mlflow | mlflow/gateway/utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/gateway/utils.py | Apache-2.0 |
async def handle_incomplete_chunks(
stream: AsyncGenerator[bytes, Any],
) -> AsyncGenerator[bytes, Any]:
"""
Wraps a streaming response and handles incomplete chunks from the server.
See https://community.openai.com/t/incomplete-stream-chunks-for-completions-api/383520
for more information.
"""
... |
Wraps a streaming response and handles incomplete chunks from the server.
See https://community.openai.com/t/incomplete-stream-chunks-for-completions-api/383520
for more information.
| handle_incomplete_chunks | python | mlflow/mlflow | mlflow/gateway/utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/gateway/utils.py | Apache-2.0 |
def _parse_chat_messages_to_prompt(messages: list[chat.RequestMessage]) -> str:
"""
This parser is based on the format described in
https://huggingface.co/blog/llama2#how-to-prompt-llama-2 .
The expected format is:
"<s>[INST] <<SYS>>
{{ system_prompt }}
... |
This parser is based on the format described in
https://huggingface.co/blog/llama2#how-to-prompt-llama-2 .
The expected format is:
"<s>[INST] <<SYS>>
{{ system_prompt }}
<</SYS>>
{{ user_msg_1 }} [/INST] {{ model_answer_1 }} </s>
<s>[... | _parse_chat_messages_to_prompt | python | mlflow/mlflow | mlflow/gateway/providers/mosaicml.py | https://github.com/mlflow/mlflow/blob/master/mlflow/gateway/providers/mosaicml.py | Apache-2.0 |
def custom_token_allowance_exceeded_handling():
"""
Context manager handler for specific error messages that are incorrectly set as server-side
errors, but are in actuality an issue with the request sent to the external provider.
"""
from fastapi import HTTPException
try:
yield
exce... |
Context manager handler for specific error messages that are incorrectly set as server-side
errors, but are in actuality an issue with the request sent to the external provider.
| custom_token_allowance_exceeded_handling | python | mlflow/mlflow | mlflow/gateway/providers/mosaicml.py | https://github.com/mlflow/mlflow/blob/master/mlflow/gateway/providers/mosaicml.py | Apache-2.0 |
async def send_request(headers: dict[str, str], base_url: str, path: str, payload: dict[str, Any]):
"""
Send an HTTP request to a specific URL path with given headers and payload.
Args:
headers: The headers to include in the request.
base_url: The base URL where the request will be sent.
... |
Send an HTTP request to a specific URL path with given headers and payload.
Args:
headers: The headers to include in the request.
base_url: The base URL where the request will be sent.
path: The specific path of the URL to which the request will be sent.
payload: The payload (o... | send_request | python | mlflow/mlflow | mlflow/gateway/providers/utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/gateway/providers/utils.py | Apache-2.0 |
def patched_class_call(original, self, *args, **kwargs):
"""
This method is used for patching class methods of gemini SDKs.
This patch creates a span and set input and output of the original method to the span.
"""
config = AutoLoggingConfig.init(flavor_name=mlflow.gemini.FLAVOR_NAME)
if config... |
This method is used for patching class methods of gemini SDKs.
This patch creates a span and set input and output of the original method to the span.
| patched_class_call | python | mlflow/mlflow | mlflow/gemini/autolog.py | https://github.com/mlflow/mlflow/blob/master/mlflow/gemini/autolog.py | Apache-2.0 |
def patched_module_call(original, *args, **kwargs):
"""
This method is used for patching standalone functions of the google.generativeai module.
This patch creates a span and set input and output of the original function to the span.
"""
config = AutoLoggingConfig.init(flavor_name=mlflow.gemini.FLAV... |
This method is used for patching standalone functions of the google.generativeai module.
This patch creates a span and set input and output of the original function to the span.
| patched_module_call | python | mlflow/mlflow | mlflow/gemini/autolog.py | https://github.com/mlflow/mlflow/blob/master/mlflow/gemini/autolog.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.