mlflow.entities
该 mlflow.entities 模块定义了由 MLflow REST API 返回的实体。
- class mlflow.entities.Assessment(name: str, source: AssessmentSource, trace_id: Optional[str] = None, run_id: Optional[str] = None, rationale: Optional[str] = None, metadata: Optional[dict[str, str]] = None, span_id: Optional[str] = None, create_time_ms: Optional[int] = None, last_update_time_ms: Optional[int] = None, assessment_id: Optional[str] = None, error: Optional[AssessmentError] = None, expectation: Optional[mlflow.entities.assessment.ExpectationValue] = None, feedback: Optional[mlflow.entities.assessment.FeedbackValue] = None, overrides: Optional[str] = None, valid: Optional[bool] = None)[source]
注意
实验性:此类可能在将来的版本中更改或在未发出警告的情况下被移除。
可附加到 trace 的 Assessment 的基类。Assessment 应为以下类型之一:
- 期望:表示特定操作的预期值的标签。
例如,聊天机器人对用户问题的期望答案。
- Feedback: 表示对操作质量的反馈的标签。
反馈可以来自不同来源,例如人工评审、启发式评分器,或 LLM-as-a-Judge。
- error: AssessmentError | None = None
- classmethod from_dictionary(d: dict[str, typing.Any]) Assessment[source]
- classmethod from_proto(proto)[source]
- source: AssessmentSource
- to_dictionary()[source]
- to_proto()[source]
- class mlflow.entities.AssessmentError(error_code: str, error_message: Optional[str] = None, stack_trace: Optional[str] = None)[source]
注意
实验性:此类可能在将来的版本中更改或在未发出警告的情况下被移除。
表示在生成评估期间发生的任何问题的错误对象。
例如,如果 LLM-as-a-Judge 无法生成反馈,您可以记录带有错误代码和消息的错误,如下所示:
from mlflow.entities import AssessmentError error = AssessmentError( error_code="RATE_LIMIT_EXCEEDED", error_message="Rate limit for the judge exceeded.", stack_trace="...", ) mlflow.log_feedback( trace_id="1234", name="faithfulness", source=AssessmentSourceType.LLM_JUDGE, error=error, # Skip setting value when an error is present )
- Parameters
error_code – The error code.
error_message – The detailed error message. Optional.
stack_trace – 错误的堆栈跟踪信息。在记录到 MLflow 之前被截断为 1000 个字符。可选。
- classmethod from_dictionary(error_dict)[source]
- classmethod from_proto(proto)[source]
- to_dictionary()[source]
- to_proto()[source]
- class mlflow.entities.AssessmentSource(source_type: str, source_id: str = 'default')[source]
注意
实验性:此类可能在将来的版本中更改或在未发出警告的情况下被移除。
评估的来源(人类、以 GPT-4 为评判者的 LLM 等)。
在记录一次评估时,MLflow 要求提供来源信息,以便跟踪评估是如何进行的。
- Parameters
source_type – 评估来源的类型。必须是 AssessmentSourceType 枚举 中的某个值或枚举值的实例。
source_id – 来源的标识符,例如用户 ID 或 LLM 判定器 ID。如果未提供,则使用默认值 “default”。
注意:
遗留的 AssessmentSourceType “AI_JUDGE” 已弃用,将被解析为 “LLM_JUDGE”。如果使用此已弃用的值,你将收到警告。此遗留术语将在未来版本的 MLflow 中移除。
示例:
人工注释可以通过源类型“HUMAN”来表示:
import mlflow from mlflow.entities.assessment import AssessmentSource, AssessmentSourceType source = AssessmentSource( source_type=AssessmentSourceType.HUMAN, # or "HUMAN" source_id="bob@example.com", )
作为裁判的 LLM 可以用源类型“LLM_JUDGE”来表示:
import mlflow from mlflow.entities.assessment import AssessmentSource, AssessmentSourceType source = AssessmentSource( source_type=AssessmentSourceType.LLM_JUDGE, # or "LLM_JUDGE" source_id="gpt-4o-mini", )
启发式评估可以用源类型为“CODE”来表示:
import mlflow from mlflow.entities.assessment import AssessmentSource, AssessmentSourceType source = AssessmentSource( source_type=AssessmentSourceType.CODE, # or "CODE" source_id="repo/evaluation_script.py", )
要记录有关评估的更多上下文,您也可以使用评估记录 APIs 的 metadata 字段。
- classmethod from_dictionary(source_dict: dict[str, typing.Any]) AssessmentSource[source]
- classmethod from_proto(proto)[source]
- to_dictionary() dict[str, typing.Any][source]
- to_proto()[source]
- class mlflow.entities.AssessmentSourceType(source_type: str)[source]
注意
实验性:此类可能在将来的版本中更改或在未发出警告的情况下被移除。
评估来源类型的枚举和校验器。
该类提供用于有效评估来源类型的常量,并处理来源类型值的验证与标准化。它支持直接访问常量以及通过字符串验证创建实例。
该类自动处理: - 忽略大小写的字符串输入(转换为大写) - 对遗留值发出弃用警告(AI_JUDGE → LLM_JUDGE) - 对来源类型值进行验证
- Available source types:
HUMAN: 由人工评估者进行的评估
LLM_JUDGE: 由 LLM 担任评判者执行的评估(例如,GPT-4)
CODE:由确定性代码/启发式方法执行的评估
SOURCE_TYPE_UNSPECIFIED: 当未指定源类型时的默认值
注意
旧的 “AI_JUDGE” 类型已弃用,并会自动转换为 “LLM_JUDGE”,同时给出弃用警告。这既确保了向后兼容,又鼓励迁移到新的术语。
示例
直接使用类常量:
from mlflow.entities.assessment import AssessmentSource, AssessmentSourceType # Direct constant usage source = AssessmentSource(source_type=AssessmentSourceType.LLM_JUDGE, source_id="gpt-4")
通过实例创建进行字符串验证:
# String input - case insensitive source = AssessmentSource( source_type="llm_judge", # Will be standardized to "LLM_JUDGE" source_id="gpt-4", ) # Deprecated value - triggers warning source = AssessmentSource( source_type="AI_JUDGE", # Warning: converts to "LLM_JUDGE" source_id="gpt-4", )
- classmethod from_proto(proto_source_type) str[source]
- class mlflow.entities.Dataset(name: str, digest: str, source_type: str, source: str, schema: Optional[str] = None, profile: Optional[str] = None)[source]
与实验相关的 Dataset 对象。
- classmethod from_proto(proto)[source]
- to_dictionary()[source]
- to_proto()[source]
- class mlflow.entities.DatasetInput(dataset: Dataset, tags: Optional[list[输入标签]] = None)[source]
与实验关联的 DatasetInput 对象。
- property dataset: Dataset
数据集.
- classmethod from_proto(proto)[source]
- property tags: list[InputTag]
输入标签的数组。
- to_dictionary()[source]
- to_proto()[source]
- class mlflow.entities.Document(page_content: str, metadata: dict[str, typing.Any] = <factory>, id: Optional[str] = None)[source]
在 MLflow Tracing 中用于表示在 RETRIEVER span 中检索到的文档的实体。
- Parameters
page_content – 文档的内容。
metadata – 与文档关联的 metadata 字典。
id – 文档的 ID。
- classmethod from_langchain_document(document)[source]
- classmethod from_llama_index_node_with_score(node_with_score)[source]
- to_dict()[source]
- class mlflow.entities.Expectation(name: str, value: Any, source: Optional[AssessmentSource] = None, trace_id: Optional[str] = None, metadata: Optional[dict[str, str]] = None, span_id: Optional[str] = None, create_time_ms: Optional[int] = None, last_update_time_ms: Optional[int] = None)[source]
注意
实验性:此类可能在将来的版本中更改或在未发出警告的情况下被移除。
表示对某个操作输出的期望,例如生成式 AI 应用针对特定用户查询应提供的预期响应。
- Parameters
name – 评估的名称。
value – 操作的预期值。 这可以是任何可被JSON序列化的值。
source – 评估的来源。如果未提供,默认来源为 HUMAN.
trace_id – 与评估关联的 trace 的 ID。如果未设置,该评估尚未与任何 trace 关联。应当指定。
metadata – 与评估相关的元数据。
span_id – 与评估关联的 span 的 ID,如果评估应与跟踪中的特定 span 关联。
create_time_ms – 评估的创建时间(以毫秒为单位)。如果未设置,则使用当前时间。
last_update_time_ms – 评估的最后更新时间(以毫秒为单位)。如果未设置,则使用当前时间。
示例
from mlflow.entities import AssessmentSource, Expectation expectation = Expectation( name="expected_response", value="The capital of France is Paris.", source=AssessmentSource( source_type=AssessmentSourceType.HUMAN, source_id="john@example.com", ), metadata={"project": "my-project"}, )
- classmethod from_proto(proto) Expectation[source]
- class mlflow.entities.Experiment(experiment_id, name, artifact_location, lifecycle_stage, tags=None, creation_time=None, last_update_time=None)[source]
Experiment 对象。
- classmethod from_proto(proto)[source]
- to_proto()[source]
- class mlflow.entities.ExperimentTag(key, value)[source]
与实验关联的 Tag 对象。
- classmethod from_proto(proto)[source]
- to_proto()[source]
- class mlflow.entities.Feedback(name: str = 'feedback', value: Optional[Union[float, int, str, bool, dict[str, float | int | str | bool], list[float | int | str | bool]]] = None, error: Optional[Union[Exception, AssessmentError]] = None, source: Optional[AssessmentSource] = None, trace_id: Optional[str] = None, metadata: Optional[dict[str, str]] = None, span_id: Optional[str] = None, create_time_ms: Optional[int] = None, last_update_time_ms: Optional[int] = None, rationale: Optional[str] = None, overrides: Optional[str] = None, valid: bool = True)[source]
注意
实验性:此类可能在将来的版本中更改或在未发出警告的情况下被移除。
表示关于一次操作输出的反馈。例如,如果生成式AI应用对特定用户查询的响应是正确的,那么人类或 LLM 评审可能会提供值为
"correct"的反馈。- Parameters
name – 评估的名称。如果未提供,默认名称“feedback”被使用。
value – 反馈值。该值可以是以下类型之一: - float - int - str - bool - list,包含上述相同类型的值 - dict,键为string,值为上述相同类型的值
error – An optional error associated with the feedback. This is used to indicate that the feedback is not valid or cannot be processed. Accepts an exception object, or an
Expectationobject.rationale – 对该反馈的理由/正当性。
source – 评估的来源。如果未提供,默认来源为 CODE.
trace_id – 与评估关联的 trace 的 ID。如果未设置,则该评估尚未与任何 trace 关联。应当指定。
metadata – 与评估相关联的 metadata。
span_id – 与评估关联的 span 的 ID(如果评估应与跟踪中的特定 span 关联)。
create_time_ms – 评估的创建时间(以毫秒为单位)。如果未设置,则使用当前时间。
last_update_time_ms – 评估的最后更新时间,单位为毫秒。如果未设置,则使用当前时间。
示例
from mlflow.entities import AssessmentSource, Feedback feedback = Feedback( name="correctness", value=True, rationale="The response is correct.", source=AssessmentSource( source_type="HUMAN", source_id="john@example.com", ), metadata={"project": "my-project"}, )
- property error_code: str | None
The error code of the error that occurred when the feedback was created.
- classmethod from_proto(proto)[source]
- class mlflow.entities.FileInfo(path, is_dir, file_size)[source]
关于文件或目录的元数据。
- classmethod from_proto(proto)[source]
- to_proto()[source]
- class mlflow.entities.InferenceTableLocation(full_table_name: str)[source]
表示 Databricks 推理表的位置。
- Parameters
full_table_name – 存放该跟踪的推理表的完全限定名称,格式为
. ..
- classmethod from_dict(d: dict[str, typing.Any]) InferenceTableLocation[source]
- classmethod from_proto(proto) InferenceTableLocation[source]
- to_dict() dict[str, typing.Any][source]
- to_proto()[source]
- class mlflow.entities.InputTag(key: str, value: str)[source]
与数据集关联的输入标签对象。
- classmethod from_proto(proto)[source]
- to_proto()[source]
- class mlflow.entities.LifecycleStage[source]
-
- classmethod is_valid(lifecycle_stage)[source]
- classmethod matches_view_type(view_type, lifecycle_stage)[source]
- classmethod view_type_to_stages(view_type=3)[source]
- class mlflow.entities.LiveSpan(otel_span: opentelemetry.trace.span.Span, trace_id: str, span_type: str = 'UNKNOWN')[source]
一个“实时”版本的
Span类。活动的 span 是在应用运行期间创建和更新的那些。当用户在代码中使用 tracing APIs 启动一个新的 span 时,会返回该活动 span 对象,以便获取和设置 span 的属性、状态、事件等。
- add_event(event: SpanEvent)[source]
向 span 添加一个事件。
- Parameters
event – 要添加到 span 的事件。该对象应该是一个
SpanEvent对象。
- record_exception(exception: str | Exception)[source]
Record an exception on the span, adding an exception event and setting span status to ERROR.
- Parameters
exception – 要记录的异常。可以是一个 Exception 实例或描述该异常的字符串。
- set_attribute(key: str, value: Any)[source]
为 span 设置单个属性。
- set_attributes(attributes: dict[str, typing.Any])[source]
将属性设置到 span。属性必须是键值对组成的字典。 该方法是累加的,即会将新属性添加到现有属性中。如果具有相同键的属性已存在,则会被覆盖。
- set_inputs(inputs: Any)[source]
将输入值设置到 span 上。
- set_outputs(outputs: Any)[source]
将输出值设置到 span。
- set_span_type(span_type: str)[source]
设置 span 的类型。
- set_status(status: SpanStatusCode | str)[source]
设置该 span 的状态。
- Parameters
status – The status of the span. This can be a
SpanStatusobject or a string representing of the status code defined inSpanStatusCodee.g."OK","ERROR".
- class mlflow.entities.LoggedModel(experiment_id: str, model_id: str, name: str, artifact_location: str, creation_timestamp: int, last_updated_timestamp: int, model_type: Optional[str] = None, source_run_id: Optional[str] = None, status: LoggedModelStatus | int = LoggedModelStatus.READY, status_message: Optional[str] = None, tags: Optional[Union[list[LoggedModelTag], dict[str, str]]] = None, params: Optional[Union[list[LoggedModelParameter], dict[str, str]]] = None, metrics: Optional[list[指标]] = None)[source]
表示已记录到 MLflow 实验中的模型的 MLflow 实体。
- classmethod from_proto(proto)[source]
- property metrics: list[指标] | None
与此模型关联的指标列表。
- property status: LoggedModelStatus
String. 此模型的当前状态。
- to_dictionary() dict[str, typing.Any][source]
- to_proto()[source]
- class mlflow.entities.LoggedModelInput(model_id: str)[source]
与 Run 关联的 ModelInput 对象。
- classmethod from_proto(proto)[source]
- to_proto()[source]
- class mlflow.entities.LoggedModelOutput(model_id: str, step: int)[source]
与 Run 关联的 ModelOutput 对象。
- classmethod from_proto(proto)[source]
- to_proto()[source]
- class mlflow.entities.LoggedModelParameter(key, value)[source]
MLflow 实体,表示模型的一个参数。
- classmethod from_proto(proto)[source]
- to_proto()[source]
- class mlflow.entities.LoggedModelStatus(value)[source]
用于表示
mlflow.entities.LoggedModel状态的枚举。- classmethod from_int(status_int: int) LoggedModelStatus[source]
- classmethod from_proto(proto)[source]
- static is_finalized(status) bool[source]
确定给定的 LoggedModelStatus 是否为已终结的状态。已终结的状态表示不会发生进一步的状态更新。
- to_int() int[source]
- to_proto()[source]
- class mlflow.entities.LoggedModelTag(key, value)[source]
与模型关联的 Tag 对象。
- classmethod from_proto(proto)[source]
- to_proto()[source]
- class mlflow.entities.Metric(key, value, timestamp, step, model_id: Optional[str] = None, dataset_name: Optional[str] = None, dataset_digest: Optional[str] = None, run_id: Optional[str] = None)[source]
指标对象。
- classmethod from_dictionary(metric_dict)[source]
从字典创建一个 Metric 对象。
- Parameters
metric_dict (dict) – 包含指标信息的字典。
- Returns
从字典创建的 Metric 对象。
- Return type
- classmethod from_proto(proto)[source]
- to_dictionary()[source]
将 Metric 对象转换为字典。
- Returns
Metric 对象表示为字典。
- Return type
dict
- to_proto()[source]
- class mlflow.entities.MlflowExperimentLocation(experiment_id: str)[source]
表示 MLflow 实验的位置。
- Parameters
experiment_id – 存储跟踪的 MLflow 实验的 ID。
- classmethod from_dict(d: dict[str, typing.Any]) MlflowExperimentLocation[source]
- classmethod from_proto(proto) MlflowExperimentLocation[source]
- to_dict() dict[str, typing.Any][source]
- to_proto()[source]
- class mlflow.entities.NoOpSpan[source]
Span 接口的无操作实现。
当 Span 创建失败时,该实例应由 mlflow.start_span 上下文管理器返回。该类应具有与 Span 完全相同的接口,以便用户的 setter 调用不会引发运行时错误。
例如。
with mlflow.start_span("span_name") as span: # Even if the span creation fails, the following calls should pass. span.set_inputs({"x": 1}) # Do something
- end(outputs: Optional[Any] = None, attributes: Optional[dict[str, typing.Any]] = None, status: Optional[Union[SpanStatus, str]] = None, end_time_ns: Optional[int] = None)[source]
- record_exception(exception: str | Exception)[source]
- set_attribute(key: str, value: Any)[source]
- set_attributes(attributes: dict[str, typing.Any])[source]
- set_inputs(inputs: dict[str, typing.Any])[source]
- set_outputs(outputs: dict[str, typing.Any])[source]
- set_status(status: SpanStatus)[source]
- class mlflow.entities.Param(key, value)[source]
参数对象。
- classmethod from_proto(proto)[source]
- to_proto()[source]
- class mlflow.entities.Prompt(name: str, description: Optional[str] = None, creation_timestamp: Optional[int] = None, tags: Optional[dict[str, str]] = None)[source]
表示 MLflow 模型注册表中一个提示的实体。
这包含提示级别的信息(名称、描述、标签),但不包含版本特定的内容。要访问诸如模板之类的版本特定内容,请使用 PromptVersion。
- class mlflow.entities.Run(run_info: RunInfo, run_data: RunData, run_inputs: Optional[RunInputs] = None, run_outputs: Optional[RunOutputs] = None)[source]
Run 对象。
- property data: RunData
运行数据,包括指标、参数和标签。
- Return type
- classmethod from_proto(proto)[source]
- property info: RunInfo
运行元数据,例如 run id、开始时间和状态。
- Return type
- property inputs: RunInputs
运行输入,包括数据集输入。
- Return type
- property outputs: RunOutputs
运行的输出,包括模型输出。
- Return type
- to_dictionary() dict[typing.Any, typing.Any][source]
- to_proto()[source]
- class mlflow.entities.RunData(metrics=None, params=None, tags=None)[source]
运行数据(指标和参数)。
- classmethod from_proto(proto)[source]
- to_dictionary()[source]
- to_proto()[source]
- class mlflow.entities.RunInfo(run_id, experiment_id, user_id, status, start_time, end_time, lifecycle_stage, artifact_uri=None, run_name=None)[source]
有关运行的元数据。
- property artifact_uri[source]
String 表示运行的根工件 URI。
- property end_time[source]
运行结束时间,以自 UNIX 纪元以来的毫秒数表示。
- classmethod from_proto(proto)[source]
- classmethod get_orderable_attributes()[source]
- classmethod get_searchable_attributes()[source]
- property lifecycle_stage
属于
LifecycleStage的值之一,用于描述该运行的生命周期阶段。
- property run_id[source]
包含 run id 的字符串。
- property run_name[source]
包含运行名称的字符串。
- property start_time[source]
运行的开始时间,单位为自 UNIX 纪元起的毫秒数。
- property status[source]
位于
mlflow.entities.RunStatus中、用于描述运行状态的值之一。
- to_proto()[source]
- property user_id[source]
发起此运行的用户的字符串 ID。
- class mlflow.entities.RunInputs(dataset_inputs: list[DatasetInput], model_inputs: Optional[list[LoggedModelInput]] = None)[source]
RunInputs 对象。
- property dataset_inputs: list[DatasetInput]
数据集输入的数组。
- classmethod from_proto(proto)[source]
- property model_inputs: list[LoggedModelInput]
模型输入的数组。
- to_dictionary() dict[str, typing.Any][source]
- to_proto()[source]
- class mlflow.entities.RunOutputs(model_outputs: list[LoggedModelOutput])[source]
RunOutputs 对象。
- classmethod from_proto(proto)[source]
- property model_outputs: list[LoggedModelOutput]
模型输出数组。
- to_dictionary() dict[typing.Any, typing.Any][source]
- to_proto()[source]
- class mlflow.entities.RunStatus[source]
表示
mlflow.entities.Run的状态的枚举。- static all_status()[source]
- static from_string(status_str)[source]
- static is_terminated(status)[source]
- static to_string(status)[source]
- class mlflow.entities.RunTag(key, value)[source]
与 run 关联的 Tag 对象。
- classmethod from_proto(proto)[source]
- to_proto()[source]
- class mlflow.entities.SourceType[source]
表示
mlflow.entities.Run的来源的枚举。- static from_string(status_str)[source]
- static to_string(status)[source]
- class mlflow.entities.Span(otel_span: opentelemetry.sdk.trace.ReadableSpan)[source]
一个 span 对象。span 表示一个工作或操作单元,是 Traces 的组成部分。
这个 Span 类表示已经完成并已持久化的不可变 span 数据。 在应用运行期间正在创建和更新的“实时” span 由
LiveSpan子类表示。- property events: list[SpanEvent]
获取该 span 的所有事件。
- Returns
该 span 的所有事件列表。
- get_attribute(key: str) Optional[Any][source]
从 span 中获取单个属性值。
- Parameters
key – 要获取的属性的键。
- Returns
该属性存在时的值,否则为 None。
- property status: SpanStatus
span的状态。
- to_dict() dict[str, typing.Any][source]
- to_proto()[source]
将其转换为与 OTLP 兼容的 proto 对象,以发送到 Databricks Trace Server。
- class mlflow.entities.SpanEvent(name: str, timestamp: int = <factory>, attributes: dict[str, typing.Union[str, bool, int, float, typing.Sequence[str], typing.Sequence[bool], typing.Sequence[int], typing.Sequence[float]]] = <factory>)[source]
一个事件,用于记录 span 期间发生的特定时刻或事件,例如抛出异常。与 OpenTelemetry 兼容。
- Parameters
name – 事件的名称。
timestamp – 事件发生的精确时间,单位为纳秒。如果未提供,将使用当前时间。
attributes – 一组键值对,用于表示事件的详细属性,例如异常堆栈跟踪。Attributes 的值必须是
[str, int, float, bool, bytes]或这些类型的序列。
- attributes: dict[str, typing.Union[str, bool, int, float, typing.Sequence[str], typing.Sequence[bool], typing.Sequence[int], typing.Sequence[float]]]
- classmethod from_exception(exception: Exception)[source]
从异常创建一个 span 事件。
- json()[source]
- to_proto()[source]
将其转换为与 OTLP 兼容的 proto 对象,以发送到 Databricks Trace Server。
- class mlflow.entities.SpanStatus(status_code: SpanStatusCode, description: str = '')[source]
span 或 trace 的状态。
- Parameters
status_code – The status code of the span or the trace. This must be one of the values of the
mlflow.entities.SpanStatusCodeenum or a string representation of it like “OK”, “ERROR”.description – Description of the status. This should be only set when the status is ERROR, otherwise it will be ignored.
- status_code: SpanStatusCode
- class mlflow.entities.SpanStatusCode(value)[source]
用于表示 span 的状态码的枚举
- static from_proto_status_code(status_code: str) SpanStatusCode[source]
将字符串状态代码转换为对应的 SpanStatusCode 枚举值。
- class mlflow.entities.SpanType[source]
预定义的一组 span 类型。
- class mlflow.entities.Trace(info: TraceInfo, data: TraceData)[source]
一个跟踪对象。
- Parameters
info – 一个包含跟踪元数据的轻量级对象。
data – 一个容器对象,用于保存 trace 的 spans 数据。
- data: TraceData
- info: TraceInfo
- static pandas_dataframe_columns() list[str][source]
- search_assessments(name: Optional[str] = None, *, span_id: Optional[str] = None, all: bool = False, type: Optional[Literal['expectation', 'feedback']] = None) list['Assessment'][source]
获取给定的 name / span ID 的评估。默认情况下,这只返回有效的评估(即未被其他评估覆盖的评估)。要返回所有评估,请指定 all=True。
- Parameters
name – 要获取的评估的名称。如果未提供,将匹配所有评估名称。
span_id – 要获取评估的 span 的 ID。 如果未提供,则会匹配所有 span。
all – 如果为 True,则返回所有评估,无论其有效性如何。
type – 要获取的评估类型(“feedback” 或 “expectation”之一)。 如果未提供,将匹配所有评估类型。
- Returns
满足给定条件的评估列表。
- search_spans(span_type: Optional[SpanType] = None, name: Optional[Union[str, re.Pattern]] = None, span_id: Optional[str] = None) list[Span][source]
在跟踪中搜索匹配给定条件的跨度。
- Parameters
span_type – 要搜索的 span 类型。
name – 要搜索的 span 的名称。它可以是一个字符串或正则表达式。
span_id – 要搜索的 span 的 ID。
- Returns
符合给定条件的 span 列表。如果没有匹配项,则返回一个空列表。
import mlflow import re from mlflow.entities import SpanType @mlflow.trace(span_type=SpanType.CHAIN) def run(x: int) -> int: x = add_one(x) x = add_two(x) x = multiply_by_two(x) return x @mlflow.trace(span_type=SpanType.TOOL) def add_one(x: int) -> int: return x + 1 @mlflow.trace(span_type=SpanType.TOOL) def add_two(x: int) -> int: return x + 2 @mlflow.trace(span_type=SpanType.TOOL) def multiply_by_two(x: int) -> int: return x * 2 # Run the function and get the trace y = run(2) trace_id = mlflow.get_last_active_trace_id() trace = mlflow.get_trace(trace_id) # 1. Search spans by name (exact match) spans = trace.search_spans(name="add_one") print(spans) # Output: [Span(name='add_one', ...)] # 2. Search spans by name (regular expression) pattern = re.compile(r"add.*") spans = trace.search_spans(name=pattern) print(spans) # Output: [Span(name='add_one', ...), Span(name='add_two', ...)] # 3. Search spans by type spans = trace.search_spans(span_type=SpanType.LLM) print(spans) # Output: [Span(name='run', ...)] # 4. Search spans by name and type spans = trace.search_spans(name="add_one", span_type=SpanType.TOOL) print(spans) # Output: [Span(name='add_one', ...)]
- to_dict() dict[str, typing.Any][source]
- to_json(pretty=False) str[source]
- to_pandas_dataframe_row() dict[str, typing.Any][source]
- to_proto()[source]
转换为要发送到 MLflow 后端的 proto 对象。
- NB: The Trace definition in MLflow backend doesn’t include the data field,
而是只包含 TraceInfoV3.
- class mlflow.entities.TraceData(spans: Optional[list[Span]] = None, **kwargs)[source]
一个保存跟踪(trace)中 span 数据的容器对象。
- Parameters
spans – 包含在该跟踪中的 spans 列表。
- classmethod from_dict(d)[source]
- property intermediate_outputs: dict[str, typing.Any] | None
返回模型或智能体在处理请求时产生的中间输出。 主要有两种返回中间输出的流程: 1. 当一个 trace 由 mlflow.log_trace API 生成时,返回该 span 的 intermediate_outputs 属性。 2. 当 trace 正常以 spans 的树结构创建时,聚合非根 spans 的输出。
- spans: list[Span]
- to_dict() dict[str, typing.Any][source]
- class mlflow.entities.TraceInfo(trace_id: str, trace_location: mlflow.entities.trace_location.TraceLocation, request_time: int, state: mlflow.entities.trace_state.TraceState, request_preview: Optional[str] = None, response_preview: Optional[str] = None, client_request_id: Optional[str] = None, execution_duration: Optional[int] = None, trace_metadata: dict[str, str] = <factory>, tags: dict[str, str] = <factory>, assessments: list[mlflow.entities.assessment.Assessment] = <factory>)[source]
有关跟踪的元数据,例如其 ID、位置、时间戳等。
- Parameters
trace_id – 跟踪的主要标识符。
trace_location – 存储跟踪的位置,以
TraceLocation对象表示。MLflow 目前支持 MLflow Experiment 或 Databricks Inference Table 作为跟踪位置。request_time – 跟踪的开始时间,单位为毫秒。
state – State of the trace, represented as a
TraceStateenum. Can be one of [OK, ERROR, IN_PROGRESS, STATE_UNSPECIFIED].request_preview – 发给模型/智能体的请求,相当于根 span 的输入,但为 JSON 编码且可能被截断。
response_preview – 来自模型/智能体的响应,相当于根 span 的输出,但经过 JSON 编码,且可能被截断。
client_request_id – 客户端提供的与该追踪相关的请求 ID。 这可用于识别来自产生该追踪的外部系统的追踪/请求,例如 Web 应用中的会话 ID。
execution_duration – 跟踪的持续时间,以毫秒为单位。
trace_metadata – 与跟踪关联的键值对。它们用于不可变的值,例如与跟踪关联的 run ID。
tags – 与该跟踪关联的标签。它们被设计为可变的值,可在跟踪创建后通过 MLflow UI 或 API 更新。
assessments – 与 trace 关联的 assessments 列表。
- assessments: list[Assessment]
- state: TraceState
- to_dict() dict[str, typing.Any][source]
将 TraceInfoV3 对象转换为字典。
- to_proto()[source]
- property token_usage: dict[str, int] | None
返回该跟踪的汇总令牌使用情况。
- Returns
一个包含该跟踪的聚合 LLM 令牌使用情况的字典。 - “input_tokens”: 输入令牌的总数。 - “output_tokens”: 输出令牌的总数。 - “total_tokens”: 输入和输出令牌之和。
注意
并非所有 LLM 提供商都支持令牌使用情况跟踪。有关哪些提供商支持令牌使用情况跟踪,请参阅 MLflow Tracing 文档。
- trace_location: TraceLocation
- class mlflow.entities.TraceLocation(type: TraceLocationType, mlflow_experiment: Optional[MlflowExperimentLocation] = None, inference_table: Optional[InferenceTableLocation] = None)[source]
表示跟踪存储的位置。
目前,MLflow 支持两种类型的跟踪位置:
MLflow 实验:跟踪存储在 MLflow 实验中。
推理表:跟踪记录存储在 Databricks 的推理表中。
- Parameters
type – 跟踪位置的类型,应为
TraceLocationType枚举值之一。mlflow_experiment – MLflow experiment 的位置。 当位置类型为 MLflow experiment 时设置此项。
inference_table – 推理表的位置。设置此项,当位置类型为 Databricks Inference table。
- classmethod from_dict(d: dict[str, typing.Any]) TraceLocation[source]
- classmethod from_experiment_id(experiment_id: str) TraceLocation[source]
- classmethod from_proto(proto) TraceLocation[source]
- inference_table: InferenceTableLocation | None = None
- mlflow_experiment: MlflowExperimentLocation | None = None
- to_dict() dict[str, typing.Any][source]
- to_proto()[source]
- type: TraceLocationType
- class mlflow.entities.TraceLocationType(value)[source]
一个枚举。
- classmethod from_dict(d: dict[str, typing.Any]) TraceLocationType[source]
- classmethod from_proto(proto: int) TraceLocationType[source]
- to_proto()[source]
- class mlflow.entities.TraceState(value)[source]
表示跟踪状态的枚举。
STATE_UNSPECIFIED: 未指定的跟踪状态。OK: 跟踪已成功完成。ERROR: Trace encountered an error.IN_PROGRESS: 跟踪正在进行中。
- static from_otel_status(otel_status: opentelemetry.trace.status.Status)[source]
将 OpenTelemetry 状态代码转换为 MLflow TraceState。
- classmethod from_proto(proto: int) TraceState[source]
- to_proto()[source]
- class mlflow.entities.ViewType[source]
用于筛选请求的实验类型的枚举。
- classmethod from_proto(proto_view_type)[source]
- classmethod from_string(view_str)[source]
- classmethod to_proto(view_type)[source]
- classmethod to_string(view_type)[source]
- class mlflow.entities.Webhook(webhook_id: str, name: str, url: str, events: list[WebhookEvent], creation_timestamp: int, last_updated_timestamp: int, description: Optional[str] = None, status: str | WebhookStatus = WebhookStatus.ACTIVE, secret: Optional[str] = None)[source]
用于 Webhook 的 MLflow 实体。
- property events: list[WebhookEvent]
- classmethod from_proto(proto: webhooks_pb2.Webhook) typing_extensions.Self[source]
- property status: WebhookStatus
- to_proto()[source]
- class mlflow.entities.WebhookEvent(entity: str | mlflow.entities.webhook.WebhookEntity, action: str | mlflow.entities.webhook.WebhookAction)[source]
表示一个包含资源和操作的 webhook 事件。
- classmethod from_proto(proto: webhooks_pb2.WebhookEvent) typing_extensions.Self[source]
- classmethod from_str(event_str: Literal['registered_model.created', 'model_version.created', 'model_version_tag.set', 'model_version_tag.deleted', 'model_version_alias.created', 'model_version_alias.deleted']) typing_extensions.Self[source]
从以点分隔的字符串表示创建一个 WebhookEvent。
- Parameters
event_str – 有效的 webhook 事件字符串(例如,“registered_model.created”)
- Returns
一个 WebhookEvent 实例
- to_proto() webhooks_pb2.WebhookEvent[source]
- class mlflow.entities.WebhookStatus(value)[source]
一个枚举。
- classmethod from_proto(proto: int) typing_extensions.Self[source]
- is_active() bool[source]
- to_proto() int[source]
- class mlflow.entities.WebhookTestResult(success: bool, response_status: Optional[int] = None, response_body: Optional[str] = None, error_message: Optional[str] = None)[source]
MLflow 用于 WebhookTestResult 的实体。
- classmethod from_proto(proto: webhooks_pb2.WebhookTestResult) typing_extensions.Self[source]
- to_proto() webhooks_pb2.WebhookTestResult[source]
- class mlflow.entities.model_registry.ModelVersion(name: str, version: str, creation_timestamp: int, last_updated_timestamp: Optional[int] = None, description: Optional[str] = None, user_id: Optional[str] = None, current_stage: Optional[str] = None, source: Optional[str] = None, run_id: Optional[str] = None, status: str = 'READY', status_message: Optional[str] = None, tags: Optional[list[ModelVersionTag]] = None, run_link: Optional[str] = None, aliases: Optional[list[str]] = None, model_id: Optional[str] = None, params: Optional[list[LoggedModelParameter]] = None, metrics: Optional[list[指标]] = None, deployment_job_state: Optional[ModelVersionDeploymentJobState] = None)[source]
MLflow 实体,用于 Model Version。
- property deployment_job_state: ModelVersionDeploymentJobState | None
当前模型版本的部署作业状态。
- classmethod from_proto(proto) ModelVersion[source]
- property metrics: list[指标] | None
与此模型版本关联的指标列表。
- property params: list[LoggedModelParameter] | None
与此模型版本关联的参数列表。
- to_proto()[source]
- class mlflow.entities.model_registry.ModelVersionDeploymentJobState(job_id, run_id, job_state, run_state, current_task_name)[source]
与模型版本关联的部署作业状态对象。
- classmethod from_proto(proto)[source]
- to_proto()[source]
- class mlflow.entities.model_registry.ModelVersionSearch(*args, **kwargs)[source]
- aliases()[source]
当前模型版本的别名列表(字符串)。
- tags()[source]
当前模型版本的标签键(字符串) -> 标签值的字典。
- class mlflow.entities.model_registry.ModelVersionTag(key, value)[source]
与模型版本关联的 Tag 对象。
- classmethod from_proto(proto)[source]
- to_proto()[source]
- class mlflow.entities.model_registry.PromptVersion(name: str, version: int, template: str | list[dict[str, typing.Any]], commit_message: Optional[str] = None, creation_timestamp: Optional[int] = None, tags: Optional[dict[str, str]] = None, aliases: Optional[list[str]] = None, last_updated_timestamp: Optional[int] = None, user_id: Optional[str] = None, response_format: Optional[Union[pydantic.main.BaseModel, dict[str, typing.Any]]] = None)[source]
表示具有其模板内容的提示的特定版本的实体。
- Parameters
name – 提示的名称。
version – 提示的版本号。
template –
提示的模板内容。可以是以下之一:
一个字符串,包含使用双大括号括起的变量,例如 {{variable}},这些变量会被format方法替换为实际值。 MLflow 使用与 Jinja2 相同的变量命名规则: https://jinja.palletsprojects.com/en/stable/api/#notes-on-identifiers
一个表示聊天消息的字典列表,其中每条消息具有 ‘role’ 和 ‘content’ 键(例如 [{“role”: “user”, “content”: “Hello {{name}}”}])
response_format – 可选的 Pydantic 类或字典,用于定义期望的响应结构。可用于为结构化输出指定模式。
commit_message – 提示版本的提交信息。可选。
creation_timestamp – 提示创建的时间戳。可选。
tags – 与 prompt version 关联的标签字典。这对于存储特定版本的信息很有用,例如变更的作者。可选。
aliases – 此提示版本的别名列表。可选。
last_updated_timestamp – 最后更新的时间戳。可选。
user_id – 创建此提示版本的用户 ID。可选。
- static convert_response_format_to_dict(response_format: pydantic.main.BaseModel | dict[str, typing.Any]) dict[str, typing.Any][source]
将响应格式规范转换为字典表示。
- Parameters
response_format – 要么是一个 Pydantic BaseModel 类,要么是一个定义响应结构的字典。
- Returns
响应格式的字典表示。如果提供了 Pydantic 类,则返回其 JSON schema。如果提供了字典,则按原样返回。
- format(allow_partial: bool = False, **kwargs) PromptVersion | str | list[dict[str, typing.Any]][source]
使用给定的关键字参数格式化模板。默认情况下,如果存在缺失的变量,会引发错误。要部分格式化提示,请设置 allow_partial=True。
示例:
# Text prompt formatting prompt = PromptVersion("my-prompt", 1, "Hello, {{title}} {{name}}!") formatted = prompt.format(title="Ms", name="Alice") print(formatted) # Output: "Hello, Ms Alice!" # Chat prompt formatting chat_prompt = PromptVersion( "assistant", 1, [ {"role": "system", "content": "You are a {{style}} assistant."}, {"role": "user", "content": "{{question}}"}, ], ) formatted = chat_prompt.format(style="friendly", question="How are you?") print(formatted) # Output: [{"role": "system", "content": "You are a friendly assistant."}, # {"role": "user", "content": "How are you?"}] # Partial formatting formatted = prompt.format(title="Ms", allow_partial=True) print(formatted) # Output: PromptVersion(name=my-prompt, version=1, template="Hello, Ms {{name}}!")
- Parameters
allow_partial – 如果为 True,允许对提示文本进行部分格式化。如果为 False,在存在缺失变量时抛出错误。
kwargs – 用于替换模板中变量的关键字参数。
- property is_text_prompt: bool
如果提示是文本提示则返回 True;如果是聊天提示则返回 False。
- Returns
True for text prompts (字符串模板), False for chat prompts (消息列表).
- property response_format: dict[str, typing.Any] | None
返回该提示的响应格式规范。
- Returns
一个字典,定义了预期的响应结构;如果未指定响应格式,则为 None。它可用于验证或结构化来自 LLM 调用的输出。
- property template: str | list[dict[str, typing.Any]]
返回提示的模板内容。
- Returns
要么是一个字符串(用于文本提示),要么是一个包含具有 ‘role’ 和 ‘content’ 键的聊天消息字典的列表(用于聊天提示)。
- to_single_brace_format() str | list[dict[str, typing.Any]][source]
将模板转换为单花括号格式。这对于与使用单花括号进行变量替换的其他系统集成非常有用,例如 LangChain 的提示模板。
- Returns
将模板中的变量从 {{variable}} 转换为 {variable} 格式。对于文本提示,返回一个字符串。对于聊天提示,返回一个消息列表。
- class mlflow.entities.model_registry.RegisteredModel(name, creation_timestamp=None, last_updated_timestamp=None, description=None, latest_versions=None, tags=None, aliases=None, deployment_job_id=None, deployment_job_state=None)[source]
用于已注册模型的 MLflow 实体。
- classmethod from_proto(proto)[source]
- property latest_versions
每个阶段的最新
mlflow.entities.model_registry.ModelVersion实例列表。
- to_proto()[source]
- class mlflow.entities.model_registry.RegisteredModelAlias(alias, version)[source]
与已注册模型关联的别名对象。
- classmethod from_proto(proto)[source]
- to_proto()[source]
- class mlflow.entities.model_registry.RegisteredModelDeploymentJobState[source]
表示已注册模型部署状态的枚举,用于
mlflow.entities.model_registry.RegisteredModel。- static all_states()[source]
- static from_string(state_str)[source]
- static to_string(state)[source]
- class mlflow.entities.model_registry.RegisteredModelSearch(*args, **kwargs)[source]
- aliases()[source]
别名字典(字符串)-> 当前已注册模型的版本。
- tags()[source]
当前已注册模型的标签键(字符串)-> 标签值的字典。