跳转到内容
AggregaAggrega
选择语言: 简体中文
本页面由机器翻译。阅读英文原文。

一个将其模型限制在 token 预算内的 APISIX 网关

一个团队将两个 OpenAI 模型放在同一个网关之后,并希望为网关每天在这些模型上的花费设定上限,以 token 计。本工作区将这样的 网关编译为 Kubernetes 清单:Apache APISIX 位于两个模型之前, 并附加了 core/period-budget。

本页还展示了语义缓存在构建之前需要从这个网关获得什么: 它能够区分的调用方(各自以其出示的密钥区分),以及一个用于存储 回复的存储。

本工作区不编写任何自有的目录实体。这里的三个实体文件 ——一个 Aggregate、一个 Manifest 和一个 Release——就是任何人需要 编写的全部内容。

它构建了什么

实例目录中的 Component它在此处的角色
gatewaycore/gateway/apisix网关,提供两个别名:assistant(来自模型 chat)和 summarizer(来自模型 mini)
chatcore/ai-model/openaiOpenAI 的 gpt-4o,以引用方式访问:集群中不为它运行任何内容
minicore/ai-model/openaiOpenAI 的 gpt-4o-mini,以同样的方式访问

两条 uses 边连接到网关的 models 插槽,每个模型各一条, 每条都以网关向该模型出示的密钥作为其 credential;两者都 读取同一个参数 openai_key,由 Release 来满足。网关上有一个 Feature 附加项 budget:Aggregate 写明计数的对象 total_tokens,以及一个限额覆盖谁的流量 gateway——即该 网关所服务的一切——而 Release 写明额度和时间跨度:每天两百万 个 token。

Manifest 将网关映射到 apisix-chart,这一实现会渲染 APISIX 项目自己的 chart(版本为 APISIX 3.18.0),并为连接到 网关的模型提供服务。连接了模型后,网关从随其一同渲染的文件中 读取路由,因此不需要 etcd 连接,也不需要 Admin API 密钥;该 Aggregate 两者都未连接。

生成示例

你可以用下面的命令构建这个示例,也可以让你的 AI 助手替你构建。

将示例写入一个以其命名的新文件夹:

Terminal window
aggrega scaffold --example apisix-token-budget

然后它会打印接下来要运行的命令。第一条命令进入新文件夹:

Terminal window
cd apisix-token-budget

构建

Terminal window
aggrega build --release release.yaml --auto-pull

release 在构建之前需要一个 lockfile,而 lockfile 是生成的而非随附发布的,因此全新克隆的仓库中没有 lockfile。请先解析出一个,或者让构建来填充它:

Terminal window
aggrega pull --release release.yaml # resolve once, then build with no flag
aggrega build --release release.yaml --auto-pull # or resolve during the build

解析会锁定网关的 Recipe 所渲染的 APISIX chart,该 chart 从其自身的仓库获取,因此需要网络。本工作区从 .aggrega-config.yaml 指定的默认注册表解析目录实体。

构建会输出如下内容,其中 <workspace> 代表本示例的文件夹:

[… omitted: two warnings, one per model connection's credential, that the declared-sensitive origin reaches the target with no per-key sensitivity marking, because the realization maps it through a valuesMapping, the resolution's summary, a notice that core/referenced-secret declares origin in both of its pillars, and a total build time, which differs per run]
Build completed: 8 files written to <workspace>/dist

借助 AI 助手

已配置 Aggrega 工具的 AI 助手也能完成同样的操作:把下面这条提示粘贴给它。

只使用 Aggrega 的工具,不要自己创建任何文件夹。如果工作区文件夹中还没有 `apisix-token-budget` 文件夹,就调用一次 `scaffold` 工具,将 `example` 设为 `apisix-token-budget`,且不提供 `dir`:它会把示例写入一个新的 `apisix-token-budget` 文件夹。然后调用 `build` 工具,将 `workspace_root` 设为 `apisix-token-budget`,`release` 设为 `release.yaml`,`auto_pull` 设为 true,`write` 设为 true。告诉我构建写入了哪些文件;它们位于 `apisix-token-budget/dist/` 下。

渲染出的目录树

dist/helm/
├── chat-service.yaml
├── gateway--assistant-zdcredential--gateway-secret-gateway-assistant-credential.yaml
├── gateway--summarizer-zdcredential--gateway-secret-gateway-summarizer-credential.yaml
├── gateway-configmap-default-gateway.yaml
├── gateway-deployment-default-gateway.yaml
├── gateway-service-default-gateway-gateway.yaml
├── mini-service.yaml
└── gateway/
└── model-routes.yaml

预算本身不生成单独的文件。它的作用被写入路由文件 dist/helm/gateway/model-routes.yaml,这是一个 ConfigMap,网关挂载它并从中读取全部路由配置。每个模型渲染出一个文件,即一个将集群内名称映射到 OpenAI API 主机的 Service;模型连接上的每个凭据各自渲染出一个 Secret,以网关和该连接的别名命名。

网关所读取的预算

以下是该 ConfigMap 的 apisix.yaml 键:

services:
- id: "model-budget"
plugins:
ai-rate-limiting:
limit: 2000000
time_window: 86400
limit_strategy: "total_tokens"
routes:
- id: "model-assistant-chat"
uri: "/assistant/v1/chat/completions"
service_id: "model-budget"
methods:
- POST
plugins:
ai-proxy:
provider: openai-compatible
auth:
header:
Authorization: "$env://AI_PROXY_ASSISTANT_AUTHORIZATION"
options:
model: "gpt-4o"
override:
endpoint: "https://api.openai.com/v1/chat/completions"
- id: "model-summarizer-chat"
uri: "/summarizer/v1/chat/completions"
service_id: "model-budget"
[… omitted: the same route for gpt-4o-mini, presenting AI_PROXY_SUMMARIZER_AUTHORIZATION]
#END

从中可以读出五点。

预算位于两条路由都引用的 service 上。 APISIX 的 token 限流 ai-rate-limiting 将计数保存在声明它的对象之下。如果写在每条路由上,它会为每条路由各保存一个计数;而只在 model-budget 上写一次,并由每条路由通过 service_id 引用它,就会为网关所服务的全部请求保存一个计数,这正是该挂载所要求的 gateway 范围。若使用 scope: model,该 Recipe 则为每个连接各写一个 service,即 model-assistant-budget 和 model-summarizer-budget,使每个模型都有各自的限额。

周期是一个以秒计的窗口。 1d 写作 86400。窗口在上一个窗口关闭后的第一个模型请求时开启,并持续该时长;它不从午夜开始。日历月没有固定的秒数,因此 1mo 会被拒绝,见下文。

单位即计数的对象。 total_tokens 是每个模型的回复所报告的读取与写入 token 之和;prompt_tokens 和 completion_tokens 只计其中一侧。网关计数的是回复所报告的内容,不做任何计价,因此它不保存以美元计的预算。

每个模型有一条 chat 路由,没有 completion 路由。 没有预算时,每个别名还会得到 /<alias>/v1/completions。APISIX 只从它能识别协议的请求中读取回复的 token,而 completion 请求的请求体携带的是 prompt 而不是 messages,不属于此类:它会得到应答,却永远不会被计数。因此在挂载预算期间不会写出该路由,completion 请求会得到 404 Route Not Found 应答。

其中不含任何密钥。 每条路由通过 APISIX 的 $env:// 引用,指明存放其连接 bearer token 的变量。以下摘自 dist/helm/gateway-deployment-default-gateway.yaml,即网关容器的 env:

env:
- name: AI_PROXY_ASSISTANT_API_KEY
valueFrom:
secretKeyRef:
key: api-key
name: gateway-assistant.credential
- name: AI_PROXY_ASSISTANT_AUTHORIZATION
value: Bearer $(AI_PROXY_ASSISTANT_API_KEY)
[… omitted: the same two variables for summarizer]

同一个 Deployment 运行一个副本,即 replicas: 1。计数保存在网关进程的内存中,因此第二个副本会保存自己的计数;在挂载预算期间,该 Recipe 将 chart 固定为一个副本。

网关在运行时做什么

对每个模型请求,网关都会将计数与 limit 比较。一旦计数达到该值,网关在窗口关闭前一律应答 503 Service Temporarily Unavailable,请求不会发送给模型;响应带有网关自己的 X-AI-RateLimit-Limit-…、 X-AI-RateLimit-Remaining-… 和 X-AI-RateLimit-Reset-… 头。一个请求的 token 在其回复完成时才计入,因此使计数达到上限的那个请求会被处理,与它同时正在进行的任何请求也会被处理。

由此产生两个结果,二者都是网关的行为,而不是配置:

  • 重启会开启一个新窗口。 计数保存在网关进程的内存中,因此滚动更新或重启后的 pod 会从零开始计数。
  • 未报告 token 的回复不计入任何数量。 计数就是每个模型报告的数量;网关会要求流式聊天请求报告其用量,而不报告用量的模型不会增加任何计数。

什么会中止构建

以下每一项都是构建打印的一句话,指明需要修改什么:

  • 以美元计的成本。 在附件中设置 unit: usd,构建会在任何内容渲染之前停止:

    [… omitted: what resolving the lockfile prints, the same halt among it, and a notice that core/referenced-secret declares origin in both of its pillars]
    [CATALOG_ERROR E0033]
    Recipe/FeatureRecipe assertions
    caused by: FeatureRecipe "period-budget-apisix" instance "gateway" assertion "unit_is_a_token_count": [… omitted: the template position and the assertion's own source]: error calling fail: assertion failed: core/period-budget attachment "budget" on "gateway" asks for unit usd, but core/gateway/apisix, which declares dataplane.aggrega.ai/period-budget: tokens, counts the tokens each model's reply reports and prices nothing, so it keeps no budget in US dollars; set unit to total_tokens, prompt_tokens or completion_tokens, or attach the Feature to a gateway that counts cost
  • 按调用方计的预算,即 scope: caller,而该 Release 未声明任何 调用方。网关根据每个调用方出示的密钥区分调用方,若没有 infra.callers,则每条路由都是开放的。声明了调用方之后(如 下一节所示),每个调用方在所有路由上都有各自的计数。

  • 日历月,即 period: 1mo,以及不是整数个 token 的限额。

  • 网关上的第二个 core/period-budget 附件,而网关在一条路由上只运行一个 token 速率限制。

  • 没有任何东西连接到 models 插座,这样就没有可供计数的模型路由。只移除这两个连接,网关自身的 Component 会先中止构建,要求提供 etcd 存储和 Admin API 密钥——没有模型的网关正是通过它们保存其路由。

  • 另一种实现。 在 Manifest 中将 core/gateway/apisix 映射到 helm/apisix, 构建会在 models 连接上停止,并指出 helm/apisix-chart:该实现运行 APISIX 3.17.0,其路由存放在 etcd 中,不渲染任何路由。它在预算附件上同样会停止,因为它 没有可写入预算的路由,而且在 3.17.0 中,每个网关进程各自 独立计数。

语义缓存需要调用方

APISIX 3.18.0 带有语义缓存,core/semantic-caching 可以附加到 这个网关上。在 aggregate.yaml 中网关的 features 里添加一个:

answers:
type: core/semantic-caching
values:
embedding_model: assistant
similarity_threshold: 0.9
ttl_seconds: 3600

Manifest 已经把该 Feature 路由到它的 APISIX 实现,构建随即 停止:

[… omitted: what resolving the lockfile prints, the same halt among it, and a notice that core/referenced-secret declares origin in both of its pillars]
[CATALOG_ERROR E0033]
Recipe/FeatureRecipe assertions
caused by: FeatureRecipe "semantic-caching-apisix" instance "gateway" assertion "scope_is_one_the_gateway_keeps": [… omitted: the template position and the assertion's own source]: error calling fail: assertion failed: core/semantic-caching attachment "answers" on "gateway" asks for scope end_user, which keeps each end user the gateway identifies apart, but core/gateway/apisix tells its callers apart only by the key each presents, and cannot tell apart the end users behind one key: a value a request names for one is whatever the caller sent, which the gateway does not verify. Set scope to key, which keeps each caller infra.callers declares apart, or attach the Feature to a gateway that identifies end users

缓存会保存一个回复,供之后提出足够相近问题的任何人使用,因此哪些人 共享同一个缓存,决定了谁可能收到为他人生成的回复。 这个网关能按每个调用方出示并经其验证的密钥把调用方彼此隔开, 但无法更细:设置 scope: key,构建会再次停止,这次是因为 尚未提供调用方:

[… omitted: what resolving the lockfile prints, the same halt among it, and a notice that core/referenced-secret declares origin in both of its pillars]
[CATALOG_ERROR E0033]
Recipe/FeatureRecipe assertions
caused by: FeatureRecipe "semantic-caching-apisix" instance "gateway" assertion "callers_are_declared": [… omitted: the template position and the assertion's own source]: error calling fail: assertion failed: core/semantic-caching attachment "answers" on "gateway" asks for scope key, but infra.callers of "gateway" declares no caller, so the gateway authenticates no key and every request on a route would share one cache, a reply generated for one caller served to another; declare the callers in infra.callers, with their keys through the caller_keys slot

做三处补充即可构建成功。Release 列出调用方及其密钥:

gateway:
infra:
callers: [support-agent, billing-agent]
features:
caller_keys:
type: core/referenced-secret-set
infra:
entries:
- key: support-agent
value: support-agent-key-change-me
- key: billing-agent
value: billing-agent-key-change-me
budget:
[… omitted: the budget's size, as above]

Aggregate 连接缓存用来把每个提示词转换为向量的模型, 以及一个存放回复的 Redis 存储,并在附加项中以 embedding_model: embedder 指定 嵌入模型,同时设置 scope: key:

models:
[… omitted: assistant and summarizer, as above]
embedder:
target: embeddings
features:
credential:
type: core/referenced-secret
values:
key: api-key
origin: "{{ .parameters.openai_key }}"
cache_store:
replies:
target: cache

其中 embeddings 组件(core/ai-model/openai-embedding,其 values.model 设为 text-embedding-3-small)和 cache 组件(core/datastore/redis)与各模型一同声明,并各自放置在 Release 中;Manifest 映射这两者,并把 core/referenced-secret-set 映射到它的 Kubernetes 实现 helm/k8s-secret-set,该实现把密钥直接写入渲染出的 Secret,因此只适用于开发目标。随后路由文件声明每个调用方并在每条路由上检查其密钥,聊天路由则带有缓存:

consumers:
- username: "support-agent"
plugins:
key-auth:
key: "$env://CALLER_SUPPORT_AGENT_AUTHORIZATION"
[… omitted: billing-agent, the same way]
routes:
- id: "model-assistant-chat"
uri: "/assistant/v1/chat/completions"
service_id: "model-budget"
methods:
- POST
plugins:
key-auth:
header: Authorization
hide_credentials: true
ai-proxy:
[… omitted: the route to gpt-4o, as above]
ai-cache:
layers:
- exact
- semantic
exact:
ttl: 3600
cache_key:
share_across_routes: false
include_consumer: true
policy: redis
redis_host: "cache-default"
redis_port: 6379
semantic:
similarity_threshold: 0.9
ttl: 3600
embedding:
openai:
endpoint: "https://api.openai.com/v1/embeddings"
model: "text-embedding-3-small"
api_key: "$env://AI_PROXY_EMBEDDER_API_KEY"
vector_search:
redis:
index: "gateway-answers"
[… omitted: the same for the other connections]

其中不含任何调用方的密钥:每个 consumer 指定一个变量,由 Deployment 从 caller_keys 附加项渲染出的 Secret 中按调用方自己的 名称填充,并组合成完整的请求头:

- name: CALLER_SUPPORT_AGENT_KEY
valueFrom:
secretKeyRef:
key: support-agent
name: gateway-caller-keys
- name: CALLER_SUPPORT_AGENT_AUTHORIZATION
value: Bearer $(CALLER_SUPPORT_AGENT_KEY)
[… omitted: the same two variables for billing-agent]

运行时,未以 Authorization: Bearer <key> 形式出示已声明密钥的请求会被拒绝,返回 HTTP 401,并且网关转发的请求中 会移除该密钥。回复按路由和调用方存储,因此某个 调用方换了措辞的提示词会得到为该调用方存储的回复,绝不会得到 为其他调用方存储的回复。从缓存返回的回复不计入 预算,超出限额后仍会返回。embedder 连接拥有 自己的路由,models 插槽上的每个连接都是如此。

编译器不做解释的地方

编译器把限额、时间窗口和计量单位作为字符串传入路由文件,并根据每个模型发布的内容传入该模型的端点和模型名称。它不会访问 OpenAI,不知道一条回复是否报告其 token 数,自身也不做任何计数。上文的每一次中止都由目录自己的实体声明,作为预算或缓存的实现中、或网关另一个 Recipe 中的断言,其中没有一次依赖于对流量的任何理解。

改编示例

  • 按模型限额。 设置 scope: model:每个别名各自获得一个服务和一份计数。
  • 按调用方限额。 按照上文“A semantic cache needs callers”中的做法,在 Release 中声明调用方及其密钥,并设置 scope: caller:每个调用方在所有路由上各自获得一份计数。
  • 只计一侧。 设置 unit: prompt_tokens 以计算模型读取的内容,或设置 completion_tokens 以计算模型写出的内容。
  • 更短或更长的窗口。 在 Release 中将 period 设置为若干秒、分钟、小时或天,例如 6h 或 30d。