路由到 LLM 提供商

简介

Agent Router 可以在一个兼容 OpenAI 的端点后接入外部 LLM 提供商。它会通过 BackendSecurityPolicy 注入各提供商的上游凭证,按模型名称进行路由,并在提供商之间进行故障转移。使用方只需调用一个内部地址,无需持有提供商密钥,因此网关成为公共云 LLM 流量的受控出口点,并将与自托管模型相同的身份、配额和计量应用于外部模型。

使用场景

  • 暴露托管模型,例如来自 OpenAI、AWS Bedrock、Azure OpenAI、GCP Vertex AI 或 Anthropic 的模型,而无需分发提供商密钥。
  • 在一个端点后,将不同的模型名称路由到不同的提供商。
  • 当主提供商不可用时,从主提供商故障转移到备用提供商。

先决条件

  1. 已安装 Alauda AI Platform Gateway,并且具备 Gateway 和 AIGatewayRoute。确认相关 CRD 已存在:

    kubectl get crd \
      aigatewayroutes.aigateway.envoyproxy.io \
      aiservicebackends.aigateway.envoyproxy.io \
      backendsecuritypolicies.aigateway.envoyproxy.io \
      backends.gateway.envoyproxy.io
  2. 已启用 Envoy Gateway Backend API。本指南使用 kind: Backend(Envoy Gateway 扩展资源)声明提供商上游,这要求在 EnvoyGateway 配置中设置 extensionApis.enableBackend: true——仅存在 CRD 并不足够。确认该项已设置;如果缺失,请启用:

    kubectl -n envoy-gateway-system get configmap envoy-gateway-config \
      -o jsonpath='{.data.envoy-gateway\.yaml}' | grep -A2 extensionApis
    # expect to see: enableBackend: true

    如果尚未设置,请在 extensionApis 下添加该项并重启控制平面:

    kubectl edit configmap envoy-gateway-config -n envoy-gateway-system
    # extensionApis:
    #   enableBackend: true
    kubectl rollout restart deployment envoy-gateway -n envoy-gateway-system
  3. 上游提供商凭证(将在下一节中创建)存储在路由命名空间中的 Secret 内。

  4. 从集群出口可以访问提供商端点。继续操作前请先验证:

    # On clusters without docker.io egress (air-gapped / mirror-only), replace
    # curlimages/curl with any small curl/wget image from your registry mirror.
    kubectl run egress-probe --rm -i --restart=Never \
      --image=curlimages/curl -- \
      curl -s -o /dev/null -w '%{http_code}\n' https://api.openai.com/v1/models
    # expect: 401  (anything other than a connection error means egress works)
NOTE

请在专用命名空间(例如 maas-system)中创建 Gateway 和 AIGatewayRoute,不要在 Envoy Gateway 控制平面命名空间 envoy-gateway-system 中创建。放置在控制平面命名空间中的网关可能不会在其监听器上应用 AI Gateway 请求处理筛选器和 SecurityPolicy,从而导致路由和策略执行无声失效。请参阅 Alauda AI Platform Gateway。

步骤

存储上游凭证

创建用于保存提供商 API 密钥的 Secret。对于 type: APIKey,数据映射键必须恰好为 apiKey——BackendSecurityPolicy 会按名称查找该字段,因此即使策略报告 Accepted,使用 --from-literal=key=... 也会导致上游调用未通过身份验证:

kubectl -n <your-namespace> create secret generic openai-key \
  --from-literal=apiKey="$OPENAI_API_KEY"   # data-map key must be 'apiKey'

使用面向后端的 BackendSecurityPolicy 注入提供商凭证。type 字段用于选择提供商身份验证方案。

apiVersion: aigateway.envoyproxy.io/v1alpha1
kind: BackendSecurityPolicy
metadata:
  name: openai-auth
  namespace: <your-namespace>
spec:
  type: APIKey
  apiKey:
    secretRef:
      name: openai-key  # Secret holding the provider API key (data key 'apiKey')
  targetRefs:
    - group: aigateway.envoyproxy.io
      kind: AIServiceBackend
      name: openai-backend

type 字段接受 APIKey、AWSCredentials、AzureAPIKey、AzureCredentials、GCPCredentials 和 AnthropicAPIKey。每种类型都需要匹配的凭证块和匹配的一组 Secret 数据键:

type凭证块必需的 Secret 数据键
APIKeyapiKey.secretRefapiKey
AWSCredentialsawsCredentials.credentialsFile.secretRefcredentials(AWS shared-credentials INI;以及内联的 region)
AzureAPIKeyazureAPIKey.secretRefapiKey
AzureCredentialsazureCredentials.clientSecretRefclient-secret(以及内联的 clientID/tenantID)
GCPCredentialsgcpCredentials.credentialsFile.secretRefservice_account.json(以及内联的 projectName/region;或者对于无密钥 WIF,使用 gcpCredentials.workloadIdentityFederationConfig)
AnthropicAPIKeyanthropicAPIKey.secretRefapiKey

当上游身份验证方案错误时,上游通常会返回 401/403。当 Secret 的键配置错误时(例如使用 key: 而不是 apiKey:),故障模式更难判断:BackendSecurityPolicy 仍会报告 Accepted=True,但控制器日志会记录 failed to get backend auth from backend security policy. Skipping this backend. ... error: secret <name> does not contain key apiKey 并从路由中移除该后端,因此对该后端的请求会超时,而不是返回明确的 401。引入新凭证时,请持续查看控制器日志:

kubectl -n envoy-gateway-system logs deploy/ai-gateway-controller -c ai-gateway-helm \
  | grep -E 'backend security policy|does not contain key'

定义提供商后端

两个资源协同工作:Backend(Envoy Gateway)告诉数据平面要访问的网络端点,而 AIServiceBackend(Agent Router)告诉 AI 筛选器要转换到的提供商架构。

首先,将上游端点声明为 Backend:

apiVersion: gateway.envoyproxy.io/v1alpha1
kind: Backend
metadata:
  name: openai-endpoint
  namespace: <your-namespace>
spec:
  endpoints:
    - fqdn:
        hostname: api.openai.com
        port: 443

然后注册提供商,将其作为引用该 Backend 的 AIServiceBackend:

apiVersion: aigateway.envoyproxy.io/v1alpha1
kind: AIServiceBackend
metadata:
  name: openai-backend
  namespace: <your-namespace>
spec:
  schema:
    name: OpenAI
  backendRef:
    name: openai-endpoint  # Backend pointing at the provider host
    kind: Backend
    group: gateway.envoyproxy.io
  • schema.name:网关必须使用的上游协议。常见值包括:OpenAI、AWSBedrock、AzureOpenAI、GCPVertexAI、Anthropic。网关会先将传入的 OpenAI-compatible 请求转换为此架构,然后再转发。
  • backendRef:必须指向 Backend(组 gateway.envoyproxy.io),而不能指向 Service——AI 筛选器依赖 Backend 处理公共端点的 FQDN + TLS。

确认两个资源均已完成调谐:

kubectl get backend,aiservicebackend -n <your-namespace>
# AIServiceBackend shows ACCEPTED=True immediately;
# the Backend STATUS column stays empty until the next step's AIGatewayRoute
# actually references this AIServiceBackend — Envoy Gateway only reconciles a
# Backend once at least one HTTPRoute targets it.

按模型路由并进行故障转移

在一个 AIGatewayRoute 规则中引用多个后端,并设置 priority,使网关从主后端故障转移到备用后端:

apiVersion: aigateway.envoyproxy.io/v1alpha1
kind: AIGatewayRoute
metadata:
  name: <aigatewayroute-name>
  namespace: <your-namespace>
spec:
  # ... parentRefs ...
  rules:
    - matches:
        - headers:
            - name: x-ai-eg-model
              type: Exact
              value: gpt-4o
      backendRefs:
        - name: openai-backend
          priority: 0   # primary
        - name: azure-backend
          priority: 1   # used when the primary is unavailable
  • matches.headers[x-ai-eg-model]:AI 筛选器会从请求正文中解析 model 字段,并将其写入此标头以进行路由。因此,请求中的 "model":"gpt-4o" 就是用于此匹配的值——调用方无需手动提供标头。
  • priority:Envoy 使用优先级级别故障转移。只要具有足够的健康端点,优先级 0 组就会承载全部流量;只有当优先级 0 降级后,优先级 1 组才会接收流量——这一行为由 Envoy 的超额配置因子和恐慌阈值控制,而不是由“优先级 0 的每个端点都必须关闭”这一严格条件控制。此 priority 字段会覆盖 Backend 级别的 fallback 设置。故障转移会自动执行,但耗时以秒计,而不是毫秒计;请勿将其作为尾部延迟预算的依据。

验证

向网关发送 OpenAI-compatible 请求,并确认请求已到达 provider,客户端的 Authorization 标头已被 BSP 注入的密钥替换,同时返回了包含令牌使用量的有效响应:

# A deliberately-bogus client Authorization to prove the gateway strips it
# and substitutes the upstream key from the BackendSecurityPolicy.
curl -sv http://<gateway-address>/v1/chat/completions \
  -H 'Authorization: Bearer client-token-that-should-be-replaced' \
  -H 'Content-Type: application/json' \
  -d '{"model":"gpt-4o","messages":[{"role":"user","content":"ping"}]}'

成功响应(200 OK,包含一个 usage 对象)表示上游凭证已注入且路由已解析。通过在 EnvoyProxy 资源上启用 Envoy 的访问日志,或暂时将流量路由到调试回显后端,检查实际发送到上游的请求;发往上游的 Authorization 标头应携带来自 openai-key Secret 的值,而不是上方的无效客户端值。

要测试故障转移,请将主 Backend 指向不可访问的主机(hostname: invalid.example.invalid)几秒钟,以模拟主后端中断,并观察流量转移到备用后端;响应正文中的 model 字段将反映新的 provider。

了解更多