跳到內容
AggregaAggregaAggregaAggrega
選擇語言: 繁體中文
本頁為機器翻譯。閱讀英文原文。

讓模型受限於 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 draft --example apisix-token-budget

它接著會印出要接著執行的命令。第一個會切換到新資料夾:

Terminal window
cd apisix-token-budget

建置

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

Release 在建置前需要鎖定檔,而鎖定檔是產生出來的、不隨附發布,所以全新複製的專案中沒有。先解析一個,或讓建置來填入:

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` 資料夾,請呼叫 `draft` 工具一次,將 `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

從中可以讀出五件事。

預算位於兩條路由都指名的服務上。 APISIX 的 token 速率限制 ai-rate-limiting 把計數保存在宣告它的物件之下。若寫在每條路由上,就會每條路由各保存一個計數;若只在 model-budget 上寫一次(每條路由都透過 service_id 指名它),就會為閘道所服務的一切保存一個計數——也就是附加項目所要求的 gateway 範圍。使用 scope: model 時,Recipe 改為每個連線寫一個服務,model-assistant-budget 與 model-summarizer-budget,因此每個模型都有自己的上限。

期間是以秒為單位的視窗。 1d 寫成 86400。視窗在前一個視窗關閉後的第一個模型請求時開啟,並持續那麼長;它不是從午夜開始。日曆月沒有固定的秒數,因此 1mo 會被拒絕,如下所述。

單位就是被計算的東西。 total_tokens 是每個模型的回覆所回報的讀取與寫入 token 合計;prompt_tokens 與 completion_tokens 計算其中一側。閘道計算回覆所回報的內容,也不為任何東西定價,因此不保存以美元計的預算。

每個模型有一條聊天路由,沒有補全路由。 沒有預算時,每個別名還會有 /<alias>/v1/completions。APISIX 只從它認得通訊協定的請求中讀取回覆的 token,而補全請求的本文帶的是 prompt 而非 messages,並不是這種請求:它會得到回答卻永遠不被計算。因此在附加預算期間,該路由不會被寫出,補全請求會得到 404 Route Not Found 的回應。

其中沒有金鑰。 每條路由都透過 APISIX 的 $env:// 參照,指名保存其連線 bearer 權杖的變數。來自 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]

其中沒有任何呼叫端的金鑰:每個使用端指名一個變數,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:每個別名各有自己的服務與計數。
  • 每個呼叫端一個上限。 在 Release 中宣告呼叫端與其金鑰,如上文「語意快取需要呼叫端」中所述,並設定 scope: caller:每個呼叫端在每條路由上各有自己的計數。
  • 計算其中一側。 設定 unit: prompt_tokens 以計算模型讀取的內容,或 completion_tokens 以計算它們寫入的內容。
  • 較短或較長的視窗。 在 Release 中把 period 設為若干秒、分鐘、小時或天,例如 6h 或 30d。