Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions changes/ai-proxy-persistent-api-key-affinity.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
## ai-proxy: opt-in persistent API Key affinity

- Add an explicitly enabled Redis-backed consumer-to-Key binding within one provider. Bind only after a successful response; retry eligible 401/402/403/429 failures with another available Key and persist a successful replacement. No plaintext API Keys are stored in Redis.
- Keep existing behavior when disabled or without a consumer identity. Enabling affinity requires Redis and supported use with token failover; this is not an account pool or quota-recovery detector.
- Stop both headers and body while awaiting Redis, preventing a provisional Key from reaching the upstream before the bound Key is resolved. Include deterministic host tests and a real Envoy/Redis timing regression harness.
- Preserve the original request URI/body through the matching internal redirect rule. Cache benefits depend on the upstream's actual isolation domain; affinity is not enabled by default and can skew Key usage for uneven consumers.
37 changes: 37 additions & 0 deletions helm/core/templates/fallback-envoyfilter.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,43 @@ spec:
name: envoy.filters.http.custom_response
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.http.custom_response.v3.CustomResponse
custom_response_matcher:
matcher_list:
matchers:
- predicate:
# Require both internal markers so ordinary routes cannot be replayed by the header alone.
and_matcher:
predicate:
- single_predicate:
input:
name: ai_proxy_api_key_retry_status
typed_config:
"@type": type.googleapis.com/envoy.type.matcher.v3.HttpResponseStatusCodeMatchInput
value_match:
exact: "299"
- single_predicate:
input:
name: ai_proxy_api_key_retry_header
typed_config:
"@type": type.googleapis.com/envoy.type.matcher.v3.HttpResponseHeaderMatchInput
header_name: x-higress-ai-proxy-key-retry
value_match:
exact: "1"
on_match:
action:
name: ai_proxy_api_key_retry
typed_config:
"@type": type.googleapis.com/envoy.extensions.http.custom_response.redirect_policy.v3.RedirectPolicy
use_original_request_uri: true
use_original_request_body: true
keep_original_response_code: false
only_redirect_upstream_code: true
max_internal_redirects: 10
request_headers_to_add:
- header:
key: x-higress-fallback-from
value: ai-proxy-key-affinity
append_action: OVERWRITE_IF_EXISTS_OR_ADD
workloadSelector:
labels:
{{- include "gateway.selectorLabels" . | nindent 6 }}
5 changes: 5 additions & 0 deletions plugins/wasm-go/extensions/ai-proxy/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,9 @@

!*/

# Reproducible runtime fixtures and reviewed synthetic evidence only.
!/test/runtime-affinity/*.py
!/test/runtime-affinity/evidence/*.json
!/test/runtime-affinity/evidence/*-log-excerpt.txt

/out
35 changes: 35 additions & 0 deletions plugins/wasm-go/extensions/ai-proxy/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ description: AI 代理插件配置参考
| `customSettings` | array of customSetting | 非必填 | - | 为 AI 请求指定覆盖或者填充参数 |
| `failover` | object | 非必填 | - | 配置 apiToken 的 failover 策略,当 apiToken 不可用时,将其移出 apiToken 列表,待健康检测通过或冷却时间到期后重新添加回 apiToken 列表 |
| `retryOnFailure` | object | 非必填 | - | 当请求失败时立即进行重试 |
| `apiKeyAffinity` | object | 非必填 | - | 按 `x-mse-consumer` 将消费者持久绑定到同一 apiToken,并在 Key 失败时切换。默认关闭,启用时必须配置 Redis。 |
| `reasoningContentMode` | string | 非必填 | - | 如何处理大模型服务返回的推理内容。目前支持以下取值:passthrough(正常输出推理内容)、ignore(不输出推理内容)、concat(将推理内容拼接在常规输出内容之前)。默认为 passthrough。仅支持通义千问服务。 |
| `capabilities` | map of string | 非必填 | - | 部分 provider 的部分 ai 能力原生兼容 openai/v1 格式,不需要重写,可以直接转发,通过此配置项指定来开启转发, key 表示的是采用的厂商协议能力,values 表示的真实的厂商该能力的 api path, 厂商协议能力当前支持: openai/v1/chatcompletions, openai/v1/embeddings, openai/v1/imagegeneration, openai/v1/audiospeech, cohere/v1/rerank |
| `basePath` | string | 非必填 | - | 如果配置了 basePath,可用于在请求 path 中移除该前缀,或添加至请求 path 中,默认为进行移除 |
Expand Down Expand Up @@ -106,6 +107,40 @@ custom-setting 会遵循如下表格,根据`name`和协议来替换对应的

`healthCheckModel` 和 `cooldownDuration` 至少需要配置一个。当两者同时配置时,apiToken 可通过健康检测提前恢复,也会在冷却时间到期后自动恢复。

`apiKeyAffinity` 的配置字段说明如下:

| 名称 | 数据类型 | 填写要求 | 默认值 | 描述 |
| ---------------- | -------- | -------------------- | ------ | -------------------------------------------------------------------- |
| enabled | bool | 非必填 | false | 是否启用 API Key 亲和 |
| redis | object | 启用亲和时必填 | - | Redis 连接配置 |
| bindingTTLDays | int | 非必填 | 7 | 绑定保留天数;成功请求到达 80% 后才续期,阈值按整天四舍五入 |
| maxRetries | int | 非必填 | 3 | 原始请求失败后最多换 Key 的次数,范围 0-10 |
| retryTimeout | int | 非必填 | 30000 | 从第一次失败开始计算的全部换 Key 时间预算,单位毫秒 |

`redis` 支持 `serviceName`、`servicePort`、`username`、`password`、`database` 和 `timeout`。`serviceName` 必填;静态服务默认端口为 80,其他服务默认端口为 6379,默认超时为 1000 毫秒。

```yaml
provider:
type: claude
apiTokens:
- key-a
- key-b
apiKeyAffinity:
enabled: true
redis:
serviceName: redis.static
servicePort: 6379
database: 0
timeout: 1000
bindingTTLDays: 7
maxRetries: 3
retryTimeout: 30000
```

开启后,同一消费者会持续使用绑定 Key。首次没有 Redis 绑定时沿用网关原有 Key 选择算法,首次成功后才写入绑定。上游返回 `401`、`402`、`403` 或 `429` 时,当前请求会在剩余可用 Key 中重试;备用 Key 返回任意 `2xx` 后才更新绑定。重试请求的上游超时会收紧到 `retryTimeout` 的剩余预算。存在可用 Key 时,亲和选择只使用 `failover` 当前可用列表;全部 Key 均不可用时,仅保留 failover 原有的首次兜底尝试,失败后不会继续在已暂停 Key 中切换。Redis 临时故障时请求继续处理,并在现有 `ai_log` 中记录 `api_key_affinity_status=redis_degraded`。

该能力不查询 Coding Plan 套餐额度,不判断日限额、周限额或恢复时间,也不提供账号池管理。流式换 Key 依赖当前版本 Helm 中的全局 `custom_response` 内部重试规则,升级插件时应同步升级网关配置。该规则仅在内部状态码 `299` 和专用重试响应头同时出现时触发,避免普通路由仅因同名响应头而重放请求。内部重试的请求体重放沿用网关已有的下游缓冲配置,本能力不额外覆盖全局请求体缓存大小。

`retryOnFailure` 的配置字段说明如下:

目前仅支持对非流式请求进行重试。
Expand Down
35 changes: 35 additions & 0 deletions plugins/wasm-go/extensions/ai-proxy/README_EN.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ Plugin execution priority: `100`
| `context` | object | Optional | - | Configuration for AI conversation context information |
| `customSettings` | array of customSetting | Optional | - | Specifies overrides or fills parameters for AI requests |
| `failover` | object | Optional | - | Configures apiToken failover. When an apiToken becomes unavailable, it is removed from the available token list and restored after a successful health check or after the cooldown period expires. |
| `apiKeyAffinity` | object | Optional | - | Persistently binds an `x-mse-consumer` consumer to one apiToken and switches Key after a failure. Disabled by default and requires Redis when enabled. |
| `basePath` | string | Optional | - | If configured, basePath can be used to remove the prefix from the request path, or prepend the prefix to the request path. Defaults to removal. |
| `basePathHandling` | string | Optional | removePrefix | basePathHandling specifies how basePath is processed. Possible values: removePrefix (removes the basePath prefix from the request path before forwarding to upstream), prepend (adds the basePath prefix to the request path when forwarding to upstream) |
| `contextCleanupCommands` | array of string | Optional | - | List of context cleanup commands. When a user message in the request exactly matches any of the configured commands, that message and all non-system messages before it will be removed, keeping only system messages and messages after the command. This enables users to actively clear conversation history. |
Expand Down Expand Up @@ -101,6 +102,40 @@ For most protocols, `custom-setting` modifies or fills parameters at the root pa

At least one of `healthCheckModel` and `cooldownDuration` must be configured when failover is enabled. If both are configured, an apiToken can be restored either by a successful health check or after the cooldown period expires.

**Details for the `apiKeyAffinity` configuration fields:**

| Name | Data Type | Requirement | Default | Description |
| ---------------- | --------- | -------------------- | ------- | --------------------------------------------------------------------------- |
| `enabled` | bool | Optional | false | Enables persistent API Key affinity |
| `redis` | object | Required when enabled| - | Redis connection configuration |
| `bindingTTLDays` | int | Optional | 7 | Binding lifetime in days; successful requests renew after the rounded 80% point |
| `maxRetries` | int | Optional | 3 | Maximum Key switches after the original failure, from 0 through 10 |
| `retryTimeout` | int | Optional | 30000 | Shared retry budget from the first failure, in milliseconds |

`redis` supports `serviceName`, `servicePort`, `username`, `password`, `database`, and `timeout`. `serviceName` is required. Static services default to port 80; other services default to 6379. The default timeout is 1000 milliseconds.

```yaml
provider:
type: claude
apiTokens:
- key-a
- key-b
apiKeyAffinity:
enabled: true
redis:
serviceName: redis.static
servicePort: 6379
database: 0
timeout: 1000
bindingTTLDays: 7
maxRetries: 3
retryTimeout: 30000
```

The same consumer keeps using its bound Key. When Redis has no binding, the first request uses the gateway's existing Key selection algorithm and persists the binding only after success. Responses `401`, `402`, `403`, and `429` retry the current request with another available Key; the binding changes only after that Key returns any `2xx`. Each retry's upstream timeout is reduced to the remaining `retryTimeout` budget. When failover has available Keys, affinity only selects from that list. If every Key is unavailable, the first attempt preserves failover's existing last-resort behavior, but a failure does not switch to another suspended Key. A temporary Redis failure fails open and records `api_key_affinity_status=redis_degraded` in the existing `ai_log`.

This feature does not query Coding Plan quotas, infer daily or weekly reset times, or manage an account pool. Streaming Key switches require the global `custom_response` internal retry rule shipped in the same Helm version, so update the gateway configuration together with the plugin. The rule triggers only when the internal `299` status and the dedicated retry response header are both present, preventing an unrelated route from replaying a request because of the header alone. Request-body replay for internal retries uses the gateway's existing downstream buffer configuration; this feature does not override the global request-body buffer size.

### Provider-Specific Configurations

#### OpenAI
Expand Down
5 changes: 4 additions & 1 deletion plugins/wasm-go/extensions/ai-proxy/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,10 @@ func (c *PluginConfig) Complete() error {
}

providerConfig := c.GetProviderConfig()
return providerConfig.SetApiTokensFailover(c.activeProvider)
if err := providerConfig.SetApiTokensFailover(c.activeProvider); err != nil {
return err
}
return providerConfig.InitApiKeyAffinity()
}

func (c *PluginConfig) GetProvider() provider.Provider {
Expand Down
Loading
Loading