MLflow Gateway Python API 详解:URI 配置、路由模型与启动实战
2026/9/12 5:41:26 网站建设 项目流程

MLflow Gateway Python API 详解:URI 配置、路由模型与启动实战

【免费下载链接】mlflowThe open source AI engineering platform for agents, LLMs, and ML models. MLflow enables teams of all sizes to debug, evaluate, monitor, and optimize production-quality AI applications while controlling costs and managing access to models and data.项目地址: https://gitcode.com/GitHub_Trending/ml/mlflow

本篇技术指南聚焦 MLflow 开源仓库中 mlflow.gateway 的 Python 侧编程接口与配置体系,覆盖set_gateway_uri/get_gateway_uri的 URI 管理、mlflow.gateway.config中的 Provider、EndpointType、EndpointConfig 等配置模型,以及如何通过 YAML 配置文件和mlflow gateway start命令启动网关服务。读完本文,你将掌握以编程方式对接 MLflow AI Gateway、编写合法网关配置、以及从源码层理解其校验与解析机制的全部要点。

从 API 参考页到真实代码

mlflow.gateway的 API 参考文档定义在 docs/api_reference/source/python_api/mlflow.gateway.rst,它是一份基于 Sphinxautomodule指令的自动生成式文档页,指定了三个被收录的 API 面:

  • mlflow.gateway模块本体,包含其所有公开成员;
  • mlflow.gateway.base_models模块的ConfigModel类;
  • mlflow.gateway.config模块(排除model_computed_fields这一实现细节)。

也就是说,这份 RST 文档最终渲染出的内容完全来自上述模块源码中的 docstring 与签名。因此,要真正理解这份 API 参考文档,必须回到源码层。本文所有结论均以当前仓库 mlflow/gateway 目录下的实现为准。

模块入口:gateway URI 的编程式管理

mlflow.gateway模块的公开 API 非常收敛,全部导出集中在 mlflow/gateway/init.py:

from mlflow.gateway.utils import get_gateway_uri, set_gateway_uri __all__ = [ "get_gateway_uri", "set_gateway_uri", ]

两个函数都实现在 mlflow/gateway/utils.py 中,它们共同构成网关客户端侧的核心状态管理。

set_gateway_uri:设定全局网关地址

set_gateway_uri(gateway_uri: str)的作用是在全局上下文中设置一个已配置且正在运行的 MLflow AI Gateway 服务器 URI。只有先设置合法 URI,才能使用网关相关的 fluent API。

函数签名与语义(源码 mlflow/gateway/utils.py#L161-L177):

def set_gateway_uri(gateway_uri: str): """Sets the uri of a configured and running MLflow AI Gateway server in a global context. Providing a valid uri and calling this function is required in order to use the MLflow AI Gateway fluent APIs. Args: gateway_uri: The full uri of a running MLflow AI Gateway server or, if running on Databricks, "databricks". """ if not _is_valid_uri(gateway_uri): raise MlflowException.invalid_parameter_value( "The gateway uri provided is missing required elements. Ensure that the schema " "and netloc are provided." ) global _gateway_uri _gateway_uri = gateway_uri

注意其中隐含的 URI 合法性校验(_is_valid_uri,见 mlflow/gateway/utils.py#L147-L158):

  • 特殊值"databricks"直接视为合法(用于 Databricks 托管环境);
  • 其余字符串必须通过urlparse解析出scheme 和 netloc(即必须形如http://127.0.0.1:5000这样的完整地址,协议头 + 域名/主机都不可缺);
  • 只提供裸主机名或不完整地址会抛出MlflowException(错误类型为invalid_parameter_value)。

典型用法:

import mlflow.gateway mlflow.gateway.set_gateway_uri("http://127.0.0.1:5000")

get_gateway_uri:读取当前网关地址

get_gateway_uri()返回当前生效的网关服务器 URI,其解析优先级如下(源码 mlflow/gateway/utils.py#L180-L195):

  1. 若此前调用过set_gateway_uri,直接返回该值;
  2. 否则回退读取环境变量MLFLOW_GATEWAY_URI
  3. 两者皆无时抛出MlflowException,提示先调用set_gateway_uri()或设置环境变量。
from mlflow.gateway import get_gateway_uri uri = get_gateway_uri() # 可能抛出 MlflowException

环境变量MLFLOW_GATEWAY_URI的定义位于 mlflow/environment_variables.py#L583,被声明为实验性(Experimental,可能变更或移除)。同文件中 mlflow/environment_variables.py#L593 还定义了MLFLOW_GATEWAY_CONFIG,用于指定网关配置文件路径,该变量会被mlflow gateway start命令作为--config-path的默认值读取(见下文 CLI 部分)。

配置模型基座:base_models 模块

RST 文档显式收录了mlflow.gateway.base_models.ConfigModel。mlflow/gateway/base_models.py 定义了四个 Pydantic 基类,它们是整个网关数据层的基石:

用途extra 策略说明
RequestModel网关请求数据(如 chat / completions 请求)allow允许额外字段,以兼容各家厂商特有的 embedding 等请求参数
ResponseModel网关响应数据(如 GetRoute 返回的路由信息)ignore忽略未知字段,保证客户端跨后端获得一致的响应体验
ConfigModel网关配置数据(如某条 OpenAI completions 路由的名称、模型名、API Key 等)ignore忽略配置中的未知字段
LimitModel网关限额数据(renewal_period、key、value 等)ignore配置类限额模型

此外还有SetLimitsModel,其字段为:

class SetLimitsModel(BaseModel, extra="ignore"): route: str limits: list[dict[str, Any]]

它对应网关 SetLimits 请求体,包含目标路由名称与限额列表。这些基类选择"请求宽松、响应与配置严格"的策略,是网关作为多厂商统一入口的关键设计:请求侧要容纳各家差异,响应侧则要保证客户端拿到稳定结构。

配置模块详解:mlflow.gateway.config

mlflow/gateway/config.py(共 661 行)是网关配置体系的核心,包含 Provider 枚举、EndpointType 枚举、各厂商配置模型、Endpoint/Route 模型以及配置文件的加载与校验函数。

Provider:支持的模型服务商

Provider枚举(mlflow/gateway/config.py#L42-L72)列出了网关可对接的全部 Provider:

openai, anthropic, cohere, ai21labs, mlflow-model-serving, mosaicml, huggingface-text-generation-inference, palm, gemini, bedrock(别名 amazon-bedrock), databricks-model-serving, databricks, mistral, togetherai, litellm, azure, groq, deepseek, xai, openrouter, ollama, vertex_ai, portkey, sap-ai-core

其中databricks-model-servingdatabricks在源码注释中明确标注"仅在 Databricks 上受支持"。Provider.values()类方法返回所有枚举值的集合,供配置校验使用。

EndpointType:三类网关端点

EndpointType枚举(mlflow/gateway/config.py#L83-L86)定义了端点的任务类型,即网关对外暴露的统一 API 形态:

枚举值含义
llm/v1/completions文本补全
llm/v1/chat对话式补全
llm/v1/embeddings向量嵌入

与之配套的GatewayRequestType枚举(mlflow/gateway/config.py#L89-L101)则进一步细分了网关内部的请求类型,包括统一的unified/chatunified/embeddings、面向各厂商的 passthrough 请求(如passthrough/model/openai-chatpassthrough/model/anthropic-messagespassthrough/model/gemini-generateContent)以及proxy/raw原始代理。

各厂商配置模型

每个 Provider 都有对应的 Pydantic 配置类,配置字段随厂商而异,这里列出有代表性的几个(全部位于 mlflow/gateway/config.py):

OpenAIConfig(L146-L194)——字段最复杂的一个:

  • openai_api_key:必填;
  • openai_api_type:枚举openai/azure/azuread,默认openai,且大小写不敏感(通过_missing_实现);
  • openai_api_base:默认https://api.openai.com/v1(当 type 为openai时);
  • openai_api_versionopenai_deployment_nameopenai_organization:可选。

_validate_field_compatibility校验器强制了字段兼容规则:当openai_api_typeopenai时不得设置openai_deployment_name;当为azure/azuread时,openai_api_baseopenai_deployment_nameopenai_api_version三者必须同时提供,且不得设置openai_organization

AnthropicConfig(L197-L204):anthropic_api_key必填,anthropic_version默认"2023-06-01"anthropic_api_base默认https://api.anthropic.com/v1

AmazonBedrockConfig(L254-L256):仅含aws_config一个字段,其类型在AWSBearerTokenAWSRoleAWSIdAndKeyAWSBaseConfig之间选择,分别对应三种 AWS 认证方式:

  • AWSRoleaws_role_arn+ 可选aws_regionsession_length_seconds默认 900 秒(15 分钟);
  • AWSIdAndKeyaws_access_key_id+aws_secret_access_key+ 可选aws_session_token
  • AWSBearerTokenaws_bearer_token

MlflowModelServingConfig(L223-L228):model_server_url,为兼容 Pydantic 对model_前缀的保留命名空间警告,显式设置了model_config = pydantic.ConfigDict(protected_namespaces=())

LiteLLMConfig(L328-L359):litellm_provider+litellm_auth_config,后者会移除 MLflow 特有的auth_mode字段,解析 API Key,并将 Databricks 的 base URL 规范化为包含/serving-endpoints的形式。

其余还有 CohereConfig、AI21LabsConfig、MosaicMLConfig、PaLMConfig、GeminiConfig、HuggingFaceTextGenerationInferenceConfig、MistralConfig、PortkeyConfig、VertexAIConfig 等。

API Key 解析机制

所有厂商配置中的 API Key 字段都经过_resolve_api_key_from_input(mlflow/gateway/config.py#L367-L407)处理,接受三种输入形式,按顺序尝试:

  1. 环境变量引用:以$开头的字符串(如"$OPENAI_API_KEY"),仅当MLFLOW_GATEWAY_RESOLVE_API_KEY_FROM_ENV环境变量为true时生效,会从环境变量中读取真实密钥;
  2. 密钥文件路径:当MLFLOW_GATEWAY_RESOLVE_API_KEY_FROM_FILEtrue时,若字符串指向一个存在的文件,则读取文件内容作为密钥;
  3. 明文密钥本身:以上两种都不命中时,直接把字符串当作密钥返回。

这套机制允许在 YAML 配置中不落盘明文密钥,而使用环境变量或密钥文件间接引用,提升安全性。需要说明的是:源码注释将其限定为 "legacy YAML-config gateway" 的解析路径,即仅用于传统配置文件方式。

EndpointConfig:端点配置模型

EndpointConfig(mlflow/gateway/config.py#L464-L562)是 YAML 配置中每个 endpoint 的对应模型,字段如下:

字段类型必填说明
namestr端点名称,只能包含 ASCII 字母数字、下划线、连字符和点(正则[a-zA-Z0-9_\-\.]+),不能含空格与 URL 保留字符
endpoint_typeEndpointType必须是上述三类端点类型之一
modelModel模型信息(name、provider、config)
limitLimit限流配置:calls(次数)、key(可选)、renewal_period(周期字符串)

limit会通过limits.parse(f"{calls}/{renewal_period}")验证语法,例如calls: 10renewal_period: "1 minute"会拼成"10/1 minute"交给限流解析器。Model模型的provider字段接受枚举字符串或已在 provider_registry 中注册的 Provider 名称,且当 provider 属于标准 Provider 集合时强制要求提供config(源码 mlflow/gateway/config.py#L480-L489 中的validate_model)。

此外还有针对模型名的语义校验(validate_route_type_and_model_name,L491-L513):

  • MosaicML 的 chat 路由只接受以受支持前缀开头的模型名;
  • AI21Labs 只接受j2-ultraj2-midj2-light三个模型。

TrafficRouteConfig:流量拆分路由

除了普通端点,配置还支持流量拆分路由(L565-L574):

class RouteDestinationConfig(ConfigModel): name: str traffic_percentage: int class TrafficRouteConfig(ConfigModel): name: str task_type: EndpointType destinations: list[RouteDestinationConfig] routing_strategy: Literal["TRAFFIC_SPLIT"] = "TRAFFIC_SPLIT"

一条路由(routes)包含名称、任务类型与多个目的地,每个目的地指向一个端点并分配流量百分比。check_configuration_route_name_collisions(mlflow/gateway/utils.py#L68-L117)会校验:

  • 端点与路由名称全局不得重复;
  • 路由目的地必须引用已存在的端点名;
  • 目的地的endpoint_type必须与路由task_type一致;
  • 每个目的地的traffic_percentage必须在 0~100 之间;
  • 同一路由所有目的地的流量百分比之和必须恰好为 100

配置文件的加载与校验

_load_gateway_config(mlflow/gateway/config.py#L623-L643)负责读取 YAML 文件:

  1. yaml.safe_load解析(解析失败报 "not a valid yaml file");
  2. 调用check_configuration_deprecated_fields拒绝已废弃的route_type键(提示改用endpoint_type);
  3. 调用check_configuration_route_name_collisions做名称冲突与流量百分比校验;
  4. 实例化GatewayConfig(endpoints=[...], routes=[...]),Pydantic 校验失败时抛出带错误详情的MlflowException

一个典型的端点 YAML 配置如下(对应_ROUTE_EXTRA_SCHEMA中给出的示例形态):

endpoints: - name: openai-completions endpoint_type: llm/v1/completions model: name: gpt-4o-mini provider: openai config: openai_api_key: $OPENAI_API_KEY

网关启动命令:mlflow gateway start

网关服务通过 CLI 子命令启动,定义在 mlflow/gateway/cli.py:

mlflow gateway start --config-path path/to/config.yaml \ --host 127.0.0.1 \ --port 5000 \ --workers 2

各选项默认值与行为(源码 mlflow/gateway/cli.py#L25-L56):

选项默认值说明
--config-path无(必填),可用环境变量MLFLOW_GATEWAY_CONFIG指定网关配置文件路径,启动前会先经_validate_config校验,非法则直接报BadParameter
--host127.0.0.1监听地址
--port5000监听端口
--workers2worker 进程数

注意两点:

  1. Windows 不支持is_windows()检查通过后会抛出ClickException("MLflow AI Gateway does not support Windows.")
  2. 已标记废弃start命令被@deprecated装饰器标注,提示迁移到新的基于 UI 的 AI Gateway(仓库内对应文档位于 docs/docs/genai 目录,参见 mlflow-ai-gateway 集成文档)。CLI 入口本身仍可用,但作为历史形态存在。

命令内部流程是:记录GatewayStartEvent遥测事件后,调用 mlflow/gateway/runner.py 中的run_app拉起应用。

流式响应与协议工具

网关客户端侧的流式处理工具集中在 mlflow/gateway/utils.py 后半部分,虽然不在mlflow.gateway__all__中,但对理解网关的 SSE 流式行为很有帮助:

  • parse_sse_lines/stream_sse_data:解析标准 SSE 格式(data:前缀行、多行块、跳过[DONE]标记);
  • handle_incomplete_chunks:处理服务端返回的不完整分块(缓冲拼接至换行边界再产出);
  • safe_stream:流式响应中途出错时(HTTP 头已发出、无法再抛 HTTPException),把异常编码为 SSE 错误块交给客户端;
  • make_streaming_response:将异步生成器包装为text/event-streamStreamingResponse
  • translate_http_exception:装饰器,把AIGatewayExceptionMlflowException翻译为 FastAPIHTTPException,这是网关 HTTP 层统一错误出口的机制。

实践要点小结

围绕mlflow.gateway的 Python API,可以从源码归纳出几条可直接落地的实践要点:

  1. URI 三段式设置:要么编程式mlflow.gateway.set_gateway_uri("http://host:port"),要么通过环境变量MLFLOW_GATEWAY_URI,二选一即可,读取时优先级前者高于后者;
  2. 配置即 Pydantic:YAML 配置会被严格解析为GatewayConfig模型,字段名、枚举值、模型名校验均在前置阶段完成,配置错误会在启动时(而非请求时)暴露;
  3. 密钥尽量不落盘:优先用$ENV_VAR引用或密钥文件路径,配合MLFLOW_GATEWAY_RESOLVE_API_KEY_FROM_ENV/MLFLOW_GATEWAY_RESOLVE_API_KEY_FROM_FILE两个开关;
  4. Azure OpenAI 有三件套约束:type 为azure/azuread时,openai_api_baseopenai_deployment_nameopenai_api_version必须同时出现;
  5. 流量拆分百分比严格校验:路由内各目的地流量百分比之和必须恰好为 100,且任务类型与目标端点必须一致;
  6. API 参考文档与源码强绑定:本页 RST 的最终内容即 mlflow/gateway/init.py、mlflow/gateway/base_models.py 与 mlflow/gateway/config.py 中 docstring 的渲染结果,阅读源码可获得比文档页更完整的字段默认值与校验规则。

【免费下载链接】mlflowThe open source AI engineering platform for agents, LLMs, and ML models. MLflow enables teams of all sizes to debug, evaluate, monitor, and optimize production-quality AI applications while controlling costs and managing access to models and data.项目地址: https://gitcode.com/GitHub_Trending/ml/mlflow

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询