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 update_assessment( self, trace_id: str, assessment_id: str, assessment: Assessment, ): """ Update an existing assessment entity in the backend store. Args: trace_id: The ID of the trace. assessment_id: The ID of the feedback assess...
Update an existing assessment entity in the backend store. Args: trace_id: The ID of the trace. assessment_id: The ID of the feedback assessment to update. assessment: The updated assessment.
update_assessment
python
mlflow/mlflow
mlflow/tracing/client.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/client.py
Apache-2.0
def delete_assessment(self, trace_id: str, assessment_id: str): """ Delete an assessment associated with a trace. Args: trace_id: The ID of the trace. assessment_id: The ID of the assessment to delete. """ if not is_databricks_uri(self.tracking_uri): ...
Delete an assessment associated with a trace. Args: trace_id: The ID of the trace. assessment_id: The ID of the assessment to delete.
delete_assessment
python
mlflow/mlflow
mlflow/tracing/client.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/client.py
Apache-2.0
def _upload_ended_trace_info( self, trace_info: TraceInfoV2, ) -> TraceInfoV2: """ Update the TraceInfo object in the backend store with the completed trace info. Args: trace_info: Updated TraceInfo object to be stored in the backend store. Returns: ...
Update the TraceInfo object in the backend store with the completed trace info. Args: trace_info: Updated TraceInfo object to be stored in the backend store. Returns: The updated TraceInfo object.
_upload_ended_trace_info
python
mlflow/mlflow
mlflow/tracing/client.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/client.py
Apache-2.0
def link_prompt_versions_to_trace( self, trace_id: str, prompts: Sequence[PromptVersion] ) -> None: """ Link multiple prompt versions to a trace. Args: trace_id: The ID of the trace to link prompts to. prompts: List of PromptVersion objects to link to the tra...
Link multiple prompt versions to a trace. Args: trace_id: The ID of the trace to link prompts to. prompts: List of PromptVersion objects to link to the trace.
link_prompt_versions_to_trace
python
mlflow/mlflow
mlflow/tracing/client.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/client.py
Apache-2.0
def _wrap_generator( fn: Callable, name: Optional[str] = None, span_type: str = SpanType.UNKNOWN, attributes: Optional[dict[str, Any]] = None, output_reducer: Optional[Callable] = None, ) -> Callable: """ Wrap a generator function to create a span. Generator functions need special handli...
Wrap a generator function to create a span. Generator functions need special handling because of its lazy evaluation nature. Let's say we have a generator function like this: ``` @mlflow.trace def generate_stream(): # B for i in range(10): # C yield i * 2...
_wrap_generator
python
mlflow/mlflow
mlflow/tracing/fluent.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/fluent.py
Apache-2.0
def start_span( name: str = "span", span_type: Optional[str] = SpanType.UNKNOWN, attributes: Optional[dict[str, Any]] = None, ) -> Generator[LiveSpan, None, None]: """ Context manager to create a new span and start it as the current span in the context. This context manager automatically manage...
Context manager to create a new span and start it as the current span in the context. This context manager automatically manages the span lifecycle and parent-child relationships. The span will be ended when the context manager exits. Any exception raised within the context manager will set the span s...
start_span
python
mlflow/mlflow
mlflow/tracing/fluent.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/fluent.py
Apache-2.0
def start_span_no_context( name: str, span_type: str = SpanType.UNKNOWN, parent_span: Optional[LiveSpan] = None, inputs: Optional[Any] = None, attributes: Optional[dict[str, str]] = None, tags: Optional[dict[str, str]] = None, experiment_id: Optional[str] = None, start_time_ns: Optional[...
Start a span without attaching it to the global tracing context. This is useful when you want to create a span without automatically linking with a parent span and instead manually manage the parent-child relationships. The span started with this function must be ended manually using the `end()` ...
start_span_no_context
python
mlflow/mlflow
mlflow/tracing/fluent.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/fluent.py
Apache-2.0
def get_trace(trace_id: str) -> Optional[Trace]: """ Get a trace by the given request ID if it exists. This function retrieves the trace from the in-memory buffer first, and if it doesn't exist, it fetches the trace from the tracking store. If the trace is not found in the tracking store, it return...
Get a trace by the given request ID if it exists. This function retrieves the trace from the in-memory buffer first, and if it doesn't exist, it fetches the trace from the tracking store. If the trace is not found in the tracking store, it returns None. Args: trace_id: The ID of the trace...
get_trace
python
mlflow/mlflow
mlflow/tracing/fluent.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/fluent.py
Apache-2.0
def get_current_active_span() -> Optional[LiveSpan]: """ Get the current active span in the global context. .. attention:: This only works when the span is created with fluent APIs like `@mlflow.trace` or `with mlflow.start_span`. If a span is created with the `mlflow.start_span_no...
Get the current active span in the global context. .. attention:: This only works when the span is created with fluent APIs like `@mlflow.trace` or `with mlflow.start_span`. If a span is created with the `mlflow.start_span_no_context` APIs, it won't be attached to the global c...
get_current_active_span
python
mlflow/mlflow
mlflow/tracing/fluent.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/fluent.py
Apache-2.0
def get_active_trace_id() -> Optional[str]: """ Get the active trace ID in the current process. This function is thread-safe. Example: .. code-block:: python :test: import mlflow @mlflow.trace def f(): trace_id = mlflow.get_active_trace_id() ...
Get the active trace ID in the current process. This function is thread-safe. Example: .. code-block:: python :test: import mlflow @mlflow.trace def f(): trace_id = mlflow.get_active_trace_id() print(trace_id) f() Returns: ...
get_active_trace_id
python
mlflow/mlflow
mlflow/tracing/fluent.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/fluent.py
Apache-2.0
def get_last_active_trace_id(thread_local: bool = False) -> Optional[str]: """ Get the **LAST** active trace in the same process if exists. .. warning:: This function is not thread-safe by default, returns the last active trace in the same process. If you want to get the last active trace ...
Get the **LAST** active trace in the same process if exists. .. warning:: This function is not thread-safe by default, returns the last active trace in the same process. If you want to get the last active trace in the current thread, set the `thread_local` parameter to True. Args...
get_last_active_trace_id
python
mlflow/mlflow
mlflow/tracing/fluent.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/fluent.py
Apache-2.0
def _set_last_active_trace_id(trace_id: str): """Internal function to set the last active trace ID.""" global _LAST_ACTIVE_TRACE_ID_GLOBAL _LAST_ACTIVE_TRACE_ID_GLOBAL = trace_id _LAST_ACTIVE_TRACE_ID_THREAD_LOCAL.set(trace_id)
Internal function to set the last active trace ID.
_set_last_active_trace_id
python
mlflow/mlflow
mlflow/tracing/fluent.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/fluent.py
Apache-2.0
def add_trace(trace: Union[Trace, dict[str, Any]], target: Optional[LiveSpan] = None): """ Add a completed trace object into another trace. This is particularly useful when you call a remote service instrumented by MLflow Tracing. By using this function, you can merge the trace from the remote serv...
Add a completed trace object into another trace. This is particularly useful when you call a remote service instrumented by MLflow Tracing. By using this function, you can merge the trace from the remote service into the current active local trace, so that you can see the full trace including what...
add_trace
python
mlflow/mlflow
mlflow/tracing/fluent.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/fluent.py
Apache-2.0
def log_trace( name: str = "Task", request: Optional[Any] = None, response: Optional[Any] = None, intermediate_outputs: Optional[dict[str, Any]] = None, attributes: Optional[dict[str, Any]] = None, tags: Optional[dict[str, str]] = None, start_time_ms: Optional[int] = None, execution_time...
Create a trace with a single root span. This API is useful when you want to log an arbitrary (request, response) pair without structured OpenTelemetry spans. The trace is linked to the active experiment. Args: name: The name of the trace (and the root span). Default to "Task". request:...
log_trace
python
mlflow/mlflow
mlflow/tracing/fluent.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/fluent.py
Apache-2.0
def _merge_trace( trace: Trace, target_trace_id: str, target_parent_span_id: str, ): """ Merge the given trace object under an existing trace in the in-memory trace registry. Args: trace: The trace object to be merged. target_trace_id: The ID of the parent trace. target_...
Merge the given trace object under an existing trace in the in-memory trace registry. Args: trace: The trace object to be merged. target_trace_id: The ID of the parent trace. target_parent_span_id: The parent span ID, under which the child trace should be merged.
_merge_trace
python
mlflow/mlflow
mlflow/tracing/fluent.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/fluent.py
Apache-2.0
def start_detached_span( name: str, parent: Optional[trace.Span] = None, experiment_id: Optional[str] = None, start_time_ns: Optional[int] = None, ) -> Optional[tuple[str, trace.Span]]: """ Start a new OpenTelemetry span that is not part of the current trace context, but with the explicit pa...
Start a new OpenTelemetry span that is not part of the current trace context, but with the explicit parent span ID if provided. Args: name: The name of the span. parent: The parent OpenTelemetry span. If not provided, the span will be created as a root span. experim...
start_detached_span
python
mlflow/mlflow
mlflow/tracing/provider.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/provider.py
Apache-2.0
def safe_set_span_in_context(span: "Span"): """ A context manager that sets the given OpenTelemetry span as the active span in the current context. Args: span: An MLflow span object to set as the active span. Example: .. code-block:: python import mlflow with mlflow...
A context manager that sets the given OpenTelemetry span as the active span in the current context. Args: span: An MLflow span object to set as the active span. Example: .. code-block:: python import mlflow with mlflow.start_span("my_span") as span: span.se...
safe_set_span_in_context
python
mlflow/mlflow
mlflow/tracing/provider.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/provider.py
Apache-2.0
def set_span_in_context(span: "Span") -> contextvars.Token: """ Set the given OpenTelemetry span as the active span in the current context. Args: span: An MLflow span object to set as the active span. Returns: A token object that will be required when detaching the span from the contex...
Set the given OpenTelemetry span as the active span in the current context. Args: span: An MLflow span object to set as the active span. Returns: A token object that will be required when detaching the span from the context.
set_span_in_context
python
mlflow/mlflow
mlflow/tracing/provider.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/provider.py
Apache-2.0
def set_destination(destination: TraceDestination): """ Set a custom span destination to which MLflow will export the traces. A destination specified by this function will take precedence over other configurations, such as tracking URI, OTLP environment variables. To reset the destination, call th...
Set a custom span destination to which MLflow will export the traces. A destination specified by this function will take precedence over other configurations, such as tracking URI, OTLP environment variables. To reset the destination, call the :py:func:`mlflow.tracing.reset()` function. Args: ...
set_destination
python
mlflow/mlflow
mlflow/tracing/provider.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/provider.py
Apache-2.0
def _get_tracer(module_name: str): """ Get a tracer instance for the given module name. If the tracer provider is not initialized, this function will initialize the tracer provider. Other simultaneous calls to this function will block until the initialization is done. """ # Initiate tracer prov...
Get a tracer instance for the given module name. If the tracer provider is not initialized, this function will initialize the tracer provider. Other simultaneous calls to this function will block until the initialization is done.
_get_tracer
python
mlflow/mlflow
mlflow/tracing/provider.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/provider.py
Apache-2.0
def _get_trace_exporter(): """ Get the exporter instance that is used by the current tracer provider. """ if _MLFLOW_TRACER_PROVIDER: processors = _MLFLOW_TRACER_PROVIDER._active_span_processor._span_processors # There should be only one processor used for MLflow tracing processo...
Get the exporter instance that is used by the current tracer provider.
_get_trace_exporter
python
mlflow/mlflow
mlflow/tracing/provider.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/provider.py
Apache-2.0
def _setup_tracer_provider(disabled=False): """ Instantiate a tracer provider and set it as the global tracer provider. Note that this function ALWAYS updates the global tracer provider, regardless of the current state. It is the caller's responsibility to ensure that the tracer provider is initialized...
Instantiate a tracer provider and set it as the global tracer provider. Note that this function ALWAYS updates the global tracer provider, regardless of the current state. It is the caller's responsibility to ensure that the tracer provider is initialized only once, and update the _MLFLOW_TRACER_PROVI...
_setup_tracer_provider
python
mlflow/mlflow
mlflow/tracing/provider.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/provider.py
Apache-2.0
def _get_mlflow_span_processor(tracking_uri: str, experiment_id: Optional[str] = None): """ Get the MLflow span processor instance that is used by the current tracer provider. """ if is_databricks_uri(tracking_uri): from mlflow.tracing.export.mlflow_v3 import MlflowV3SpanExporter from ml...
Get the MLflow span processor instance that is used by the current tracer provider.
_get_mlflow_span_processor
python
mlflow/mlflow
mlflow/tracing/provider.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/provider.py
Apache-2.0
def disable(): """ Disable tracing. .. note:: This function sets up `OpenTelemetry` to use `NoOpTracerProvider <https://github.com/open-telemetry/opentelemetry-python/blob/4febd337b019ea013ccaab74893bd9883eb59000/opentelemetry-api/src/opentelemetry/trace/__init__.py#L222>`_ and eff...
Disable tracing. .. note:: This function sets up `OpenTelemetry` to use `NoOpTracerProvider <https://github.com/open-telemetry/opentelemetry-python/blob/4febd337b019ea013ccaab74893bd9883eb59000/opentelemetry-api/src/opentelemetry/trace/__init__.py#L222>`_ and effectively disables all ...
disable
python
mlflow/mlflow
mlflow/tracing/provider.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/provider.py
Apache-2.0
def enable(): """ Enable tracing. Example: .. code-block:: python :test: import mlflow @mlflow.trace def f(): return 0 # Tracing is enabled by default f() assert len(mlflow.search_traces()) == 1 # Disable tracing ...
Enable tracing. Example: .. code-block:: python :test: import mlflow @mlflow.trace def f(): return 0 # Tracing is enabled by default f() assert len(mlflow.search_traces()) == 1 # Disable tracing mlflow.tracing.disab...
enable
python
mlflow/mlflow
mlflow/tracing/provider.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/provider.py
Apache-2.0
def trace_disabled(f): """ A decorator that temporarily disables tracing for the duration of the decorated function. .. code-block:: python @trace_disabled def f(): with mlflow.start_span("my_span") as span: span.set_attribute("my_key", "my_value") ...
A decorator that temporarily disables tracing for the duration of the decorated function. .. code-block:: python @trace_disabled def f(): with mlflow.start_span("my_span") as span: span.set_attribute("my_key", "my_value") return # This functi...
trace_disabled
python
mlflow/mlflow
mlflow/tracing/provider.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/provider.py
Apache-2.0
def reset(): """ Reset the flags that indicates whether the MLflow tracer provider has been initialized. This ensures that the tracer provider is re-initialized when next tracing operation is performed. """ # Set NoOp tracer provider to reset the global tracer to the initial state. _setup_tr...
Reset the flags that indicates whether the MLflow tracer provider has been initialized. This ensures that the tracer provider is re-initialized when next tracing operation is performed.
reset
python
mlflow/mlflow
mlflow/tracing/provider.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/provider.py
Apache-2.0
def is_tracing_enabled() -> bool: """ Check if tracing is enabled based on whether the global tracer is instantiated or not. Trace is considered as "enabled" if the followings 1. The default state (before any tracing operation) 2. The tracer is not either ProxyTracer or NoOpTracer """ i...
Check if tracing is enabled based on whether the global tracer is instantiated or not. Trace is considered as "enabled" if the followings 1. The default state (before any tracing operation) 2. The tracer is not either ProxyTracer or NoOpTracer
is_tracing_enabled
python
mlflow/mlflow
mlflow/tracing/provider.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/provider.py
Apache-2.0
def register_trace(self, otel_trace_id: int, trace_info: TraceInfo): """ Register a new trace info object to the in-memory trace registry. Args: otel_trace_id: The OpenTelemetry trace ID for the new trace. trace_info: The trace info object to be stored. """ ...
Register a new trace info object to the in-memory trace registry. Args: otel_trace_id: The OpenTelemetry trace ID for the new trace. trace_info: The trace info object to be stored.
register_trace
python
mlflow/mlflow
mlflow/tracing/trace_manager.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/trace_manager.py
Apache-2.0
def register_span(self, span: LiveSpan): """ Store the given span in the in-memory trace data. Args: span: The span to be stored. """ if not isinstance(span, LiveSpan): _logger.debug(f"Invalid span object {type(span)} is passed. Skipping.") re...
Store the given span in the in-memory trace data. Args: span: The span to be stored.
register_span
python
mlflow/mlflow
mlflow/tracing/trace_manager.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/trace_manager.py
Apache-2.0
def get_span_from_id(self, trace_id: str, span_id: str) -> Optional[LiveSpan]: """ Get a span object for the given trace_id and span_id. """ with self._lock: trace = self._traces.get(trace_id) return trace.span_dict.get(span_id) if trace else None
Get a span object for the given trace_id and span_id.
get_span_from_id
python
mlflow/mlflow
mlflow/tracing/trace_manager.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/trace_manager.py
Apache-2.0
def get_root_span_id(self, trace_id) -> Optional[str]: """ Get the root span ID for the given trace ID. """ with self._lock: trace = self._traces.get(trace_id) if trace: for span in trace.span_dict.values(): if span.parent_id is None: ...
Get the root span ID for the given trace ID.
get_root_span_id
python
mlflow/mlflow
mlflow/tracing/trace_manager.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/trace_manager.py
Apache-2.0
def set_trace_metadata(self, trace_id: str, key: str, value: str): """ Set the trace metadata for the given request ID. """ with self.get_trace(trace_id) as trace: if trace: trace.info.trace_metadata[key] = value
Set the trace metadata for the given request ID.
set_trace_metadata
python
mlflow/mlflow
mlflow/tracing/trace_manager.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/trace_manager.py
Apache-2.0
def pop_trace(self, otel_trace_id: int) -> Optional[ManagerTrace]: """ Pop trace data for the given OpenTelemetry trace ID and return it as a ManagerTrace wrapper containing the trace and prompts. """ with self._lock: mlflow_trace_id = self._otel_id_to_mlflow_trace_id...
Pop trace data for the given OpenTelemetry trace ID and return it as a ManagerTrace wrapper containing the trace and prompts.
pop_trace
python
mlflow/mlflow
mlflow/tracing/trace_manager.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/trace_manager.py
Apache-2.0
def _check_timeout_update(self): """ TTL/Timeout may be updated by users after initial cache creation. This method checks for the update and create a new cache instance with the updated timeout. """ new_timeout = MLFLOW_TRACE_TIMEOUT_SECONDS.get() if new_timeout != getatt...
TTL/Timeout may be updated by users after initial cache creation. This method checks for the update and create a new cache instance with the updated timeout.
_check_timeout_update
python
mlflow/mlflow
mlflow/tracing/trace_manager.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/trace_manager.py
Apache-2.0
def reset(cls): """Clear all the aggregated trace data. This should only be used for testing.""" if cls._instance: with cls._instance._lock: cls._instance._traces.clear() cls._instance = None
Clear all the aggregated trace data. This should only be used for testing.
reset
python
mlflow/mlflow
mlflow/tracing/trace_manager.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/trace_manager.py
Apache-2.0
def handle(self) -> None: """Handle the task execution. This method must not raise any exception.""" try: self.handler(*self.args) except Exception as e: _logger.warning( f"{self.error_msg} Error: {e}.", exc_info=_logger.isEnabledFor(loggin...
Handle the task execution. This method must not raise any exception.
handle
python
mlflow/mlflow
mlflow/tracing/export/async_export_queue.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/export/async_export_queue.py
Apache-2.0
def put(self, task: Task): """Put a new task to the queue for processing.""" if not self.is_active(): self.activate() # If stop event is set, wait for the queue to be drained before putting the task if self._stop_event.is_set(): self._stop_event.wait() t...
Put a new task to the queue for processing.
put
python
mlflow/mlflow
mlflow/tracing/export/async_export_queue.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/export/async_export_queue.py
Apache-2.0
def _dispatch_task(self) -> None: """Dispatch a task from the queue to the worker thread pool.""" # NB: Monitor number of active tasks being processed by the workers. If the all # workers are busy, wait for one of them to finish before draining a new task # from the queue. This is be...
Dispatch a task from the queue to the worker thread pool.
_dispatch_task
python
mlflow/mlflow
mlflow/tracing/export/async_export_queue.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/export/async_export_queue.py
Apache-2.0
def activate(self) -> None: """Activate the async queue to accept and handle incoming tasks.""" with self._lock: if self._is_active: return self._set_up_threads() # Callback to ensure remaining tasks are processed before program exit if n...
Activate the async queue to accept and handle incoming tasks.
activate
python
mlflow/mlflow
mlflow/tracing/export/async_export_queue.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/export/async_export_queue.py
Apache-2.0
def _set_up_threads(self) -> None: """Set up the consumer and worker threads.""" with self._lock: self._worker_threadpool = ThreadPoolExecutor( max_workers=self._max_workers, thread_name_prefix="MlflowTraceLoggingWorker", ) self._consum...
Set up the consumer and worker threads.
_set_up_threads
python
mlflow/mlflow
mlflow/tracing/export/async_export_queue.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/export/async_export_queue.py
Apache-2.0
def _at_exit_callback(self) -> None: """Callback function executed when the program is exiting.""" try: _logger.info( "Flushing the async trace logging queue before program exit. " "This may take a while..." ) self.flush(terminate=True)...
Callback function executed when the program is exiting.
_at_exit_callback
python
mlflow/mlflow
mlflow/tracing/export/async_export_queue.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/export/async_export_queue.py
Apache-2.0
def flush(self, terminate=False) -> None: """ Flush the async logging queue. Args: terminate: If True, shut down the logging threads after flushing. """ if not self.is_active(): return self._stop_event.set() self._consumer_thread.join() ...
Flush the async logging queue. Args: terminate: If True, shut down the logging threads after flushing.
flush
python
mlflow/mlflow
mlflow/tracing/export/async_export_queue.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/export/async_export_queue.py
Apache-2.0
def export(self, spans: Sequence[ReadableSpan]): """ Export the spans to Inference Table via the TTLCache buffer. Args: spans: A sequence of OpenTelemetry ReadableSpan objects passed from a span processor. Only root spans for each trace should be exported. ""...
Export the spans to Inference Table via the TTLCache buffer. Args: spans: A sequence of OpenTelemetry ReadableSpan objects passed from a span processor. Only root spans for each trace should be exported.
export
python
mlflow/mlflow
mlflow/tracing/export/inference_table.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/export/inference_table.py
Apache-2.0
def export(self, spans: Sequence[ReadableSpan]): """ Export the spans to MLflow backend. Args: spans: A sequence of OpenTelemetry ReadableSpan objects passed from a span processor. Only root spans for each trace should be exported. """ for span in spa...
Export the spans to MLflow backend. Args: spans: A sequence of OpenTelemetry ReadableSpan objects passed from a span processor. Only root spans for each trace should be exported.
export
python
mlflow/mlflow
mlflow/tracing/export/mlflow_v2.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/export/mlflow_v2.py
Apache-2.0
def _log_trace(self, trace: Trace): """Log the trace to MLflow backend.""" upload_trace_data_task = Task( handler=self._client._upload_trace_data, args=(trace.info, trace.data), error_msg="Failed to log trace to MLflow backend.", ) upload_ended_trace_...
Log the trace to MLflow backend.
_log_trace
python
mlflow/mlflow
mlflow/tracing/export/mlflow_v2.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/export/mlflow_v2.py
Apache-2.0
def export(self, spans: Sequence[ReadableSpan]): """ Export the spans to the destination. Args: spans: A sequence of OpenTelemetry ReadableSpan objects passed from a span processor. Only root spans for each trace should be exported. """ for span in sp...
Export the spans to the destination. Args: spans: A sequence of OpenTelemetry ReadableSpan objects passed from a span processor. Only root spans for each trace should be exported.
export
python
mlflow/mlflow
mlflow/tracing/export/mlflow_v3.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/export/mlflow_v3.py
Apache-2.0
def _log_trace(self, trace: Trace, prompts: Sequence[PromptVersion]): """ Handles exporting a trace to MLflow using the V3 API and blob storage. Steps: 1. Create the trace in MLflow 2. Upload the trace data to blob storage using the returned trace info. """ try: ...
Handles exporting a trace to MLflow using the V3 API and blob storage. Steps: 1. Create the trace in MLflow 2. Upload the trace data to blob storage using the returned trace info.
_log_trace
python
mlflow/mlflow
mlflow/tracing/export/mlflow_v3.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/export/mlflow_v3.py
Apache-2.0
def try_link_prompts_to_trace( client: TracingClient, trace_id: str, prompts: Sequence[PromptVersion], synchronous: bool = True, ) -> None: """ Attempt to link prompt versions to a trace with graceful error handling. This function provides a reusable way to link prompts to traces with consi...
Attempt to link prompt versions to a trace with graceful error handling. This function provides a reusable way to link prompts to traces with consistent error handling across different exporters. Errors are caught and logged but do not propagate, ensuring that prompt linking failures don't affect trac...
try_link_prompts_to_trace
python
mlflow/mlflow
mlflow/tracing/export/utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/export/utils.py
Apache-2.0
def _link_prompts_sync( client: TracingClient, trace_id: str, prompts: Sequence[PromptVersion], ) -> None: """ Synchronously link prompt versions to a trace with error handling. This is the core implementation that handles the actual API call and error logging. Args: client: The Tr...
Synchronously link prompt versions to a trace with error handling. This is the core implementation that handles the actual API call and error logging. Args: client: The TracingClient instance to use for linking. trace_id: The ID of the trace to link prompts to. prompts: Sequence o...
_link_prompts_sync
python
mlflow/mlflow
mlflow/tracing/export/utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/export/utils.py
Apache-2.0
def on_start(self, span: OTelSpan, parent_context: Optional[Context] = None): """ Handle the start of a span. This method is called when an OpenTelemetry span is started. Args: span: An OpenTelemetry Span object that is started. parent_context: The context of the span. N...
Handle the start of a span. This method is called when an OpenTelemetry span is started. Args: span: An OpenTelemetry Span object that is started. parent_context: The context of the span. Note that this is only passed when the context object is explicitly specif...
on_start
python
mlflow/mlflow
mlflow/tracing/processor/base_mlflow.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/processor/base_mlflow.py
Apache-2.0
def on_end(self, span: OTelReadableSpan) -> None: """ Handle the end of a span. This method is called when an OpenTelemetry span is ended. Args: span: An OpenTelemetry ReadableSpan object that is ended. """ # Processing the trace only when the root span is found. ...
Handle the end of a span. This method is called when an OpenTelemetry span is ended. Args: span: An OpenTelemetry ReadableSpan object that is ended.
on_end
python
mlflow/mlflow
mlflow/tracing/processor/base_mlflow.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/processor/base_mlflow.py
Apache-2.0
def _get_experiment_id_for_trace(self, span: OTelReadableSpan) -> str: """ Determine the experiment ID to associate with the trace. The experiment ID can be configured in multiple ways, in order of precedence: 1. An experiment ID specified via the span creation API i.e. MlflowClient()...
Determine the experiment ID to associate with the trace. The experiment ID can be configured in multiple ways, in order of precedence: 1. An experiment ID specified via the span creation API i.e. MlflowClient().start_trace() 2. An experiment ID specified via the processor construct...
_get_experiment_id_for_trace
python
mlflow/mlflow
mlflow/tracing/processor/base_mlflow.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/processor/base_mlflow.py
Apache-2.0
def _update_trace_info(self, trace: _Trace, root_span: OTelReadableSpan): """Update the trace info with the final values from the root span.""" # The trace/span start time needs adjustment to exclude the latency of # the backend API call. We already adjusted the span start time in the # ...
Update the trace info with the final values from the root span.
_update_trace_info
python
mlflow/mlflow
mlflow/tracing/processor/base_mlflow.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/processor/base_mlflow.py
Apache-2.0
def _truncate_metadata(self, value: Optional[str]) -> str: """Get truncated value of the attribute if it exceeds the maximum length.""" if not value: return "" if len(value) > MAX_CHARS_IN_TRACE_INFO_METADATA: trunc_length = MAX_CHARS_IN_TRACE_INFO_METADATA - len(TRUNCAT...
Get truncated value of the attribute if it exceeds the maximum length.
_truncate_metadata
python
mlflow/mlflow
mlflow/tracing/processor/base_mlflow.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/processor/base_mlflow.py
Apache-2.0
def on_start(self, span: OTelSpan, parent_context: Optional[Context] = None): """ Handle the start of a span. This method is called when an OpenTelemetry span is started. Args: span: An OpenTelemetry Span object that is started. parent_context: The context of the span. N...
Handle the start of a span. This method is called when an OpenTelemetry span is started. Args: span: An OpenTelemetry Span object that is started. parent_context: The context of the span. Note that this is only passed when the context object is explicitly specif...
on_start
python
mlflow/mlflow
mlflow/tracing/processor/inference_table.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/processor/inference_table.py
Apache-2.0
def _start_trace(self, root_span: OTelSpan) -> TraceInfoV2: """ Create a new TraceInfo object and register it with the trace manager. This method is called in the on_start method of the base class. """ trace_info = TraceInfo( trace_id=generate_trace_id_v3(root_span),...
Create a new TraceInfo object and register it with the trace manager. This method is called in the on_start method of the base class.
_start_trace
python
mlflow/mlflow
mlflow/tracing/processor/mlflow_v3.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/processor/mlflow_v3.py
Apache-2.0
def get_artifact_uri_for_trace(trace_info: Union[TraceInfoV2, TraceInfo]): """ Get the artifact uri for accessing the trace data. The artifact root is specified in the trace tags, which is set when logging the trace in the backend. Args: trace_info: Either a TraceInfo or TraceInfoV3 object...
Get the artifact uri for accessing the trace data. The artifact root is specified in the trace tags, which is set when logging the trace in the backend. Args: trace_info: Either a TraceInfo or TraceInfoV3 object containing trace metadata. Returns: The artifact URI string for the ...
get_artifact_uri_for_trace
python
mlflow/mlflow
mlflow/tracing/utils/artifact_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/utils/artifact_utils.py
Apache-2.0
def resolve_env_metadata(): """ Resolve common environment metadata to be saved in the trace info. These should not # change over time, so we resolve them only once. These will be stored in trace # metadata rather than tags, because they are immutable. """ # GitRunContext does not property work ...
Resolve common environment metadata to be saved in the trace info. These should not # change over time, so we resolve them only once. These will be stored in trace # metadata rather than tags, because they are immutable.
resolve_env_metadata
python
mlflow/mlflow
mlflow/tracing/utils/environment.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/utils/environment.py
Apache-2.0
def raise_as_trace_exception(f): """ A decorator to make sure that the decorated function only raises MlflowTracingException. Any exceptions are caught and translated to MlflowTracingException before exiting the function. This is helpful for upstream functions to handle tracing related exceptions prope...
A decorator to make sure that the decorated function only raises MlflowTracingException. Any exceptions are caught and translated to MlflowTracingException before exiting the function. This is helpful for upstream functions to handle tracing related exceptions properly.
raise_as_trace_exception
python
mlflow/mlflow
mlflow/tracing/utils/exception.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/utils/exception.py
Apache-2.0
def do_once(self, func: Callable[[], None]): """ Execute ``func`` if it hasn't been executed or return. Will block until ``func`` has been called by one thread. """ if self.__done: return with self.__lock: if not self.__done: func(...
Execute ``func`` if it hasn't been executed or return. Will block until ``func`` has been called by one thread.
do_once
python
mlflow/mlflow
mlflow/tracing/utils/once.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/utils/once.py
Apache-2.0
def get_otlp_exporter() -> SpanExporter: """ Get the OTLP exporter based on the configured protocol. """ endpoint = _get_otlp_endpoint() protocol = _get_otlp_protocol() if protocol == "grpc": try: from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExpor...
Get the OTLP exporter based on the configured protocol.
get_otlp_exporter
python
mlflow/mlflow
mlflow/tracing/utils/otlp.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/utils/otlp.py
Apache-2.0
def _get_otlp_endpoint() -> Optional[str]: """ Get the OTLP endpoint from the environment variables. Ref: https://opentelemetry.io/docs/languages/sdk-configuration/otlp-exporter/#endpoint-configuration """ # Use `or` instead of default value to do lazy eval return os.environ.get("OTEL_EXPORTER_O...
Get the OTLP endpoint from the environment variables. Ref: https://opentelemetry.io/docs/languages/sdk-configuration/otlp-exporter/#endpoint-configuration
_get_otlp_endpoint
python
mlflow/mlflow
mlflow/tracing/utils/otlp.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/utils/otlp.py
Apache-2.0
def traces_to_df(traces: list[Trace]) -> "pandas.DataFrame": """ Convert a list of MLflow Traces to a pandas DataFrame with one column called "traces" containing string representations of each Trace. """ import pandas as pd from mlflow.entities.trace import Trace # import here to avoid circula...
Convert a list of MLflow Traces to a pandas DataFrame with one column called "traces" containing string representations of each Trace.
traces_to_df
python
mlflow/mlflow
mlflow/tracing/utils/search.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/utils/search.py
Apache-2.0
def extract_span_inputs_outputs( traces: Union[list["mlflow.entities.Trace"], "pandas.DataFrame"], fields: list[str], col_name: Optional[str] = None, ) -> "pandas.DataFrame": """ Extracts the specified input and output fields from the spans contained in the specified traces. Args: trace...
Extracts the specified input and output fields from the spans contained in the specified traces. Args: traces: A list of :py:class:`mlflow.entities.Trace` or a pandas DataFrame containing traces. fields: A list of field strings of the form 'span_name.[inputs|outputs]' or 'span_name...
extract_span_inputs_outputs
python
mlflow/mlflow
mlflow/tracing/utils/search.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/utils/search.py
Apache-2.0
def consume_until_char_or_end(self, stop_char: Optional[str] = None) -> str: """ Consume characters until the specified character is encountered or the end of the string. If char is None, consume until the end of the string. """ consumed = "" while (c := self.peek()) and ...
Consume characters until the specified character is encountered or the end of the string. If char is None, consume until the end of the string.
consume_until_char_or_end
python
mlflow/mlflow
mlflow/tracing/utils/search.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/utils/search.py
Apache-2.0
def _extract_from_traces_pandas_df( df: "pandas.DataFrame", col_name: str, fields: list[_ParsedField] ) -> "pandas.DataFrame": """ Extracts the specified fields from the spans contained in the specified column of the specified traces DataFrame. """ from mlflow.entities import Span if col_n...
Extracts the specified fields from the spans contained in the specified column of the specified traces DataFrame.
_extract_from_traces_pandas_df
python
mlflow/mlflow
mlflow/tracing/utils/search.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/utils/search.py
Apache-2.0
def _find_matching_value(field: _ParsedField, spans: list["mlflow.entities.Span"]) -> Optional[Any]: """ Find the value of the field in the list of spans. If the field is not found, return None. """ for span in spans: span_inputs_or_outputs = getattr(span, field.field_type) if ( ...
Find the value of the field in the list of spans. If the field is not found, return None.
_find_matching_value
python
mlflow/mlflow
mlflow/tracing/utils/search.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/utils/search.py
Apache-2.0
def _extract_spans_from_row( row_content: Optional[list[dict[str, Any]]], ) -> list["mlflow.entities.Span"]: """ Parses and extracts MLflow Spans from the row content of a traces pandas DataFrame. """ from mlflow.entities import Span if row_content is None: return [] try: r...
Parses and extracts MLflow Spans from the row content of a traces pandas DataFrame.
_extract_spans_from_row
python
mlflow/mlflow
mlflow/tracing/utils/search.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/utils/search.py
Apache-2.0
def get_trace_cache_with_timeout() -> Cache: """ Return a cache object that stores traces in-memory while they are in-progress. If the timeout is specified, this returns a customized cache that logs the expired traces to the backend. Otherwise, this returns a regular cache. """ if timeout := M...
Return a cache object that stores traces in-memory while they are in-progress. If the timeout is specified, this returns a customized cache that logs the expired traces to the backend. Otherwise, this returns a regular cache.
get_trace_cache_with_timeout
python
mlflow/mlflow
mlflow/tracing/utils/timeout.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/utils/timeout.py
Apache-2.0
def __setitem__(self, key, value, cache_setitem=Cache.__setitem__): """Set the item in the cache, and also in the linked list if it is a new key""" with self.timer as time: cache_setitem(self, key, value) if key not in self._links: # Add the new item to the tail of the l...
Set the item in the cache, and also in the linked list if it is a new key
__setitem__
python
mlflow/mlflow
mlflow/tracing/utils/timeout.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/utils/timeout.py
Apache-2.0
def __delitem__(self, key, cache_delitem=Cache.__delitem__): """Delete the item from the cache and the linked list.""" cache_delitem(self, key) link = self._links.pop(key) link.unlink()
Delete the item from the cache and the linked list.
__delitem__
python
mlflow/mlflow
mlflow/tracing/utils/timeout.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/utils/timeout.py
Apache-2.0
def expire(self, time=None): """ Trigger the expiration of traces that have exceeded the timeout. Args: time: Unused. Only for compatibility with the parent class. """ expired = self._get_expired_traces() # End the expired traces and set the status to ERROR ...
Trigger the expiration of traces that have exceeded the timeout. Args: time: Unused. Only for compatibility with the parent class.
expire
python
mlflow/mlflow
mlflow/tracing/utils/timeout.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/utils/timeout.py
Apache-2.0
def _get_expired_traces(self) -> list[str]: """ Find all expired traces and return their request IDs. The linked list is ordered by expiration time, so we can traverse the list from the head and return early whenever we find a trace that has not expired yet. """ time = s...
Find all expired traces and return their request IDs. The linked list is ordered by expiration time, so we can traverse the list from the head and return early whenever we find a trace that has not expired yet.
_get_expired_traces
python
mlflow/mlflow
mlflow/tracing/utils/timeout.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/utils/timeout.py
Apache-2.0
def set_request_response_preview(trace_info: TraceInfo, trace_data: TraceData) -> None: """ Set the request and response previews for the trace info. """ # If request/response preview is already set by users via `mlflow.update_current_trace`, # we don't override it with the truncated version. if...
Set the request and response previews for the trace info.
set_request_response_preview
python
mlflow/mlflow
mlflow/tracing/utils/truncation.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/utils/truncation.py
Apache-2.0
def _get_truncated_preview(request_or_response: Optional[str], role: str) -> str: """ Truncate the request preview to fit the max length. """ if request_or_response is None: return "" if len(request_or_response) <= TRACE_REQUEST_RESPONSE_PREVIEW_MAX_LENGTH: return request_or_respons...
Truncate the request preview to fit the max length.
_get_truncated_preview
python
mlflow/mlflow
mlflow/tracing/utils/truncation.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/utils/truncation.py
Apache-2.0
def _get_last_message(messages: list[dict[str, Any]], role: str) -> Optional[dict[str, Any]]: """ Return last message with the given role. If the messages don't include a message with the given role, return the last one. """ for message in reversed(messages): if message.get("role") == role: ...
Return last message with the given role. If the messages don't include a message with the given role, return the last one.
_get_last_message
python
mlflow/mlflow
mlflow/tracing/utils/truncation.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/utils/truncation.py
Apache-2.0
def suppress_warning(module: str, message: str): """ Convert the "Failed to detach context" log raised by the OpenTelemetry logger to DEBUG level so that it does not show up in the user's console. Args: module: The module name of the logger that raises the warning. message: The (part of...
Convert the "Failed to detach context" log raised by the OpenTelemetry logger to DEBUG level so that it does not show up in the user's console. Args: module: The module name of the logger that raises the warning. message: The (part of) message in the log that needs to be demoted to DEBUG l...
suppress_warning
python
mlflow/mlflow
mlflow/tracing/utils/warning.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/utils/warning.py
Apache-2.0
def request_id_backward_compatible(func): """ A decorator to support backward compatibility for the `request_id` parameter, which is deprecated and replaced by the `trace_id` parameter in tracing APIs. This decorator will adds `request_id` to the function signature and issue a deprecation warning i...
A decorator to support backward compatibility for the `request_id` parameter, which is deprecated and replaced by the `trace_id` parameter in tracing APIs. This decorator will adds `request_id` to the function signature and issue a deprecation warning if `request_id` is used with non-null value.
request_id_backward_compatible
python
mlflow/mlflow
mlflow/tracing/utils/warning.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/utils/warning.py
Apache-2.0
def _is_safe_to_encode_str(self, obj) -> bool: """Check if it's safe to encode the object as a string.""" try: # These Llama Index objects are not safe to encode as string, because their __str__ # method consumes the stream and make it unusable. # E.g. https://github....
Check if it's safe to encode the object as a string.
_is_safe_to_encode_str
python
mlflow/mlflow
mlflow/tracing/utils/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/utils/__init__.py
Apache-2.0
def build_otel_context(trace_id: int, span_id: int) -> trace_api.SpanContext: """ Build an OpenTelemetry SpanContext object from the given trace and span IDs. """ return trace_api.SpanContext( trace_id=trace_id, span_id=span_id, # NB: This flag is OpenTelemetry's concept to indic...
Build an OpenTelemetry SpanContext object from the given trace and span IDs.
build_otel_context
python
mlflow/mlflow
mlflow/tracing/utils/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/utils/__init__.py
Apache-2.0
def deduplicate_span_names_in_place(spans: list[LiveSpan]): """ Deduplicate span names in the trace data by appending an index number to the span name. This is only applied when there are multiple spans with the same name. The span names are modified in place to avoid unnecessary copying. E.g. ...
Deduplicate span names in the trace data by appending an index number to the span name. This is only applied when there are multiple spans with the same name. The span names are modified in place to avoid unnecessary copying. E.g. ["red", "red"] -> ["red_1", "red_2"] ["red", "red", "b...
deduplicate_span_names_in_place
python
mlflow/mlflow
mlflow/tracing/utils/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/utils/__init__.py
Apache-2.0
def aggregate_usage_from_spans(spans: list[LiveSpan]) -> Optional[dict[str, int]]: """Aggregate token usage information from all spans in the trace.""" input_tokens, output_tokens, total_tokens = 0, 0, 0 has_usage_data = False span_id_to_spans = {span.span_id: span for span in spans} for span in sp...
Aggregate token usage information from all spans in the trace.
aggregate_usage_from_spans
python
mlflow/mlflow
mlflow/tracing/utils/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/utils/__init__.py
Apache-2.0
def get_otel_attribute(span: trace_api.Span, key: str) -> Optional[str]: """ Get the attribute value from the OpenTelemetry span in a decoded format. Args: span: The OpenTelemetry span object. key: The key of the attribute to retrieve. Returns: The attribute value as decoded st...
Get the attribute value from the OpenTelemetry span in a decoded format. Args: span: The OpenTelemetry span object. key: The key of the attribute to retrieve. Returns: The attribute value as decoded string. If the attribute is not found or cannot be parsed, return None. ...
get_otel_attribute
python
mlflow/mlflow
mlflow/tracing/utils/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/utils/__init__.py
Apache-2.0
def maybe_get_request_id(is_evaluate=False) -> Optional[str]: """Get the request ID if the current prediction is as a part of MLflow model evaluation.""" context = _try_get_prediction_context() if not context or (is_evaluate and not context.is_evaluate): return None if not context.request_id an...
Get the request ID if the current prediction is as a part of MLflow model evaluation.
maybe_get_request_id
python
mlflow/mlflow
mlflow/tracing/utils/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/utils/__init__.py
Apache-2.0
def construct_full_inputs(func, *args, **kwargs) -> dict[str, Any]: """ Construct the full input arguments dictionary for the given function, including positional and keyword arguments. """ signature = inspect.signature(func) # this does not create copy. So values should not be mutated directly ...
Construct the full input arguments dictionary for the given function, including positional and keyword arguments.
construct_full_inputs
python
mlflow/mlflow
mlflow/tracing/utils/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/utils/__init__.py
Apache-2.0
def maybe_set_prediction_context(context: Optional["Context"]): """ Set the prediction context if the given context is not None. Otherwise no-op. """ if not IS_TRACING_SDK_ONLY and context: from mlflow.pyfunc.context import set_prediction_context with set_prediction_context(context)...
Set the prediction context if the given context is not None. Otherwise no-op.
maybe_set_prediction_context
python
mlflow/mlflow
mlflow/tracing/utils/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/utils/__init__.py
Apache-2.0
def set_span_chat_messages( span: LiveSpan, messages: list[Union[dict, ChatMessage]], append=False, ): """ Set the `mlflow.chat.messages` attribute on the specified span. This attribute is used in the UI, and also by downstream applications that consume trace data, such as MLflow evaluate. ...
Set the `mlflow.chat.messages` attribute on the specified span. This attribute is used in the UI, and also by downstream applications that consume trace data, such as MLflow evaluate. Args: span: The LiveSpan to add the attribute to messages: A list of standardized chat messages (refer...
set_span_chat_messages
python
mlflow/mlflow
mlflow/tracing/utils/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/utils/__init__.py
Apache-2.0
def set_span_chat_tools(span: LiveSpan, tools: list[ChatTool]): """ Set the `mlflow.chat.tools` attribute on the specified span. This attribute is used in the UI, and also by downstream applications that consume trace data, such as MLflow evaluate. Args: span: The LiveSpan to add the attrib...
Set the `mlflow.chat.tools` attribute on the specified span. This attribute is used in the UI, and also by downstream applications that consume trace data, such as MLflow evaluate. Args: span: The LiveSpan to add the attribute to tools: A list of standardized chat tool definitions (ref...
set_span_chat_tools
python
mlflow/mlflow
mlflow/tracing/utils/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/utils/__init__.py
Apache-2.0
def set_chat_attributes_special_case(span: LiveSpan, inputs: Any, outputs: Any): """ Set the `mlflow.chat.messages` and `mlflow.chat.tools` attributes on the specified span based on the inputs and outputs of the function. Usually those attributes are set by autologging integrations. This utility functi...
Set the `mlflow.chat.messages` and `mlflow.chat.tools` attributes on the specified span based on the inputs and outputs of the function. Usually those attributes are set by autologging integrations. This utility function handles special cases where we want to set chat attributes for manually created s...
set_chat_attributes_special_case
python
mlflow/mlflow
mlflow/tracing/utils/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/utils/__init__.py
Apache-2.0
def add_size_bytes_to_trace_metadata(trace: Trace): """ Calculate the size of the trace in bytes and add it as a tag to the trace. This method modifies the trace object in place by adding a new tag. Note: For simplicity, we calculate the size without considering the size metadata itself. This prov...
Calculate the size of the trace in bytes and add it as a tag to the trace. This method modifies the trace object in place by adding a new tag. Note: For simplicity, we calculate the size without considering the size metadata itself. This provides a close approximation without requiring complex calcul...
add_size_bytes_to_trace_metadata
python
mlflow/mlflow
mlflow/tracing/utils/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/utils/__init__.py
Apache-2.0
def update_trace_state_from_span_conditionally(trace, root_span): """ Update trace state from span status, but only if the user hasn't explicitly set a different trace status. This utility preserves user-set trace status while maintaining default behavior for traces that haven't been explicitly con...
Update trace state from span status, but only if the user hasn't explicitly set a different trace status. This utility preserves user-set trace status while maintaining default behavior for traces that haven't been explicitly configured. Used by trace processors when converting traces to an export...
update_trace_state_from_span_conditionally
python
mlflow/mlflow
mlflow/tracing/utils/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracing/utils/__init__.py
Apache-2.0
def get_artifact_uri(run_id, artifact_path=None, tracking_uri=None): """Get the absolute URI of the specified artifact in the specified run. If `path` is not specified the artifact root URI of the specified run will be returned; calls to ``log_artifact`` and ``log_artifacts`` write artifact(s) to subdirecto...
Get the absolute URI of the specified artifact in the specified run. If `path` is not specified the artifact root URI of the specified run will be returned; calls to ``log_artifact`` and ``log_artifacts`` write artifact(s) to subdirectories of the artifact root URI. Args: run_id: The ID of the run ...
get_artifact_uri
python
mlflow/mlflow
mlflow/tracking/artifact_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracking/artifact_utils.py
Apache-2.0
def _get_root_uri_and_artifact_path(artifact_uri): """Parse the artifact_uri to get the root_uri and artifact_path. Args: artifact_uri: The *absolute* URI of the artifact. """ if os.path.exists(artifact_uri): if not is_windows(): # If we're dealing with local files, just ref...
Parse the artifact_uri to get the root_uri and artifact_path. Args: artifact_uri: The *absolute* URI of the artifact.
_get_root_uri_and_artifact_path
python
mlflow/mlflow
mlflow/tracking/artifact_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracking/artifact_utils.py
Apache-2.0
def _download_artifact_from_uri(artifact_uri, output_path=None, lineage_header_info=None): """ Args: artifact_uri: The *absolute* URI of the artifact to download. output_path: The local filesystem path to which to download the artifact. If unspecified, a local output path will be cre...
Args: artifact_uri: The *absolute* URI of the artifact to download. output_path: The local filesystem path to which to download the artifact. If unspecified, a local output path will be created. lineage_header_info: The model lineage header info to be consumed by lineage service...
_download_artifact_from_uri
python
mlflow/mlflow
mlflow/tracking/artifact_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracking/artifact_utils.py
Apache-2.0
def _upload_artifacts_to_databricks( source, run_id, source_host_uri=None, target_databricks_profile_uri=None ): """Copy the artifacts from ``source`` to the destination Databricks workspace (DBFS) given by ``databricks_profile_uri`` or the current tracking URI. Args: source: Source location fo...
Copy the artifacts from ``source`` to the destination Databricks workspace (DBFS) given by ``databricks_profile_uri`` or the current tracking URI. Args: source: Source location for the artifacts to copy. run_id: Run ID to associate the artifacts with. source_host_uri: Specifies the sour...
_upload_artifacts_to_databricks
python
mlflow/mlflow
mlflow/tracking/artifact_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracking/artifact_utils.py
Apache-2.0
def __init__(self, tracking_uri: Optional[str] = None, registry_uri: Optional[str] = None): """ Args: tracking_uri: Address of local or remote tracking server. If not provided, defaults to the service set by ``mlflow.tracking.set_tracking_uri``. See `Where Run...
Args: tracking_uri: Address of local or remote tracking server. If not provided, defaults to the service set by ``mlflow.tracking.set_tracking_uri``. See `Where Runs Get Recorded <../tracking.html#where-runs-get-recorded>`_ for more info. ...
__init__
python
mlflow/mlflow
mlflow/tracking/client.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracking/client.py
Apache-2.0
def _get_registry_client(self): """Attempts to create a ModelRegistryClient if one does not already exist. Raises: MlflowException: If the ModelRegistryClient cannot be created. This may occur, for example, when the registry URI refers to an unsupported store type (e.g., the ...
Attempts to create a ModelRegistryClient if one does not already exist. Raises: MlflowException: If the ModelRegistryClient cannot be created. This may occur, for example, when the registry URI refers to an unsupported store type (e.g., the FileStore). Returns: ...
_get_registry_client
python
mlflow/mlflow
mlflow/tracking/client.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracking/client.py
Apache-2.0
def get_parent_run(self, run_id: str) -> Optional[Run]: """Gets the parent run for the given run id if one exists. Args: run_id: Unique identifier for the child run. Returns: A single :py:class:`mlflow.entities.Run` object, if the parent run exists. Otherwise, ...
Gets the parent run for the given run id if one exists. Args: run_id: Unique identifier for the child run. Returns: A single :py:class:`mlflow.entities.Run` object, if the parent run exists. Otherwise, returns None. .. code-block:: python :test:...
get_parent_run
python
mlflow/mlflow
mlflow/tracking/client.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracking/client.py
Apache-2.0
def create_run( self, experiment_id: str, start_time: Optional[int] = None, tags: Optional[dict[str, Any]] = None, run_name: Optional[str] = None, ) -> Run: """ Create a :py:class:`mlflow.entities.Run` object that can be associated with metrics, parame...
Create a :py:class:`mlflow.entities.Run` object that can be associated with metrics, parameters, artifacts, etc. Unlike :py:func:`mlflow.projects.run`, creates objects but does not run code. Unlike :py:func:`mlflow.start_run`, does not change the "active run" used by :py:func:`m...
create_run
python
mlflow/mlflow
mlflow/tracking/client.py
https://github.com/mlflow/mlflow/blob/master/mlflow/tracking/client.py
Apache-2.0