모델을 토큰 예산 안에서 운용하는 APISIX 게이트웨이
한 팀이 두 개의 OpenAI 모델을 하나의 게이트웨이 뒤에 두고, 게이트웨이가 이 모델들에 하루에 쓰는 양에
토큰 단위로 상한을 두려고 합니다. 이 워크스페이스는 그러한 게이트웨이를 Kubernetes 매니페스트로
컴파일합니다. 두 모델 앞에 Apache APISIX를 두고,
core/period-budget을 연결합니다.
이 페이지에서는 또한 시맨틱 캐시가 구성되기 전에 이 게이트웨이에 무엇을 요구하는지도 보여 줍니다. 즉 각자가 제시하는 키로 서로 구별할 수 있는 호출자와, 응답을 저장할 저장소입니다.
이 워크스페이스는 자체 카탈로그 엔티티를 작성하지 않습니다. 여기 있는 세 개의 엔티티 파일, 즉 Aggregate, Manifest, Release가 누구든 작성하는 내용의 전부입니다.
구성되는 내용
| 인스턴스 | 카탈로그 Component | 여기서의 역할 |
|---|---|---|
gateway | core/gateway/apisix | 두 개의 별칭을 제공하는 게이트웨이: 모델 chat에서 오는 assistant와 모델 mini에서 오는 summarizer |
chat | core/ai-model/openai | 참조로 연결되는 OpenAI의 gpt-4o: 클러스터에서는 이를 위해 아무것도 실행되지 않습니다 |
mini | core/ai-model/openai | 같은 방식으로 연결되는 OpenAI의 gpt-4o-mini |
게이트웨이의 models 소켓으로 들어가는 uses 엣지가 두 개 있으며, 각 모델에 하나씩 연결되고,
각각 게이트웨이가 해당 모델에 제시하는 키를 credential로 전달합니다. 두 엣지 모두
하나의 파라미터 openai_key를 읽으며, 이는 Release가 채웁니다. 게이트웨이에는 Feature
부착이 하나 있는데, budget입니다. Aggregate는 무엇을 셀지인 total_tokens와 하나의 한도가 누구의 트래픽을 포괄하는지인 gateway, 즉 게이트웨이가
제공하는 모든 것을 작성하고, Release는 얼마만큼, 얼마의 기간 동안인지를 작성합니다. 하루 2백만
토큰입니다.
Manifest는 게이트웨이를 apisix-chart에 매핑합니다. 이는 프로젝트 자체의 APISIX chart를
APISIX 3.18.0으로 렌더링하고, 게이트웨이에 연결된 모델을 제공하는 realization입니다. 모델이 연결되어 있으면
게이트웨이는 함께 렌더링된 파일에서 라우트를 읽으므로 etcd 연결도 Admin API 키도 받지 않습니다.
Aggregate는 둘 다 연결하지 않습니다.
예제 생성하기
아래 명령으로 이 예제를 빌드하거나, AI 어시스턴트에게 대신 빌드하게 할 수 있습니다.
예제 이름을 딴 새 폴더에 예제를 씁니다:
aggrega scaffold --example apisix-token-budget그런 다음 이어서 실행할 명령을 출력합니다. 첫 번째 명령은 새 폴더로 이동합니다:
cd apisix-token-budget빌드
aggrega build --release release.yaml --auto-pullrelease는 빌드하기 전에 lockfile이 필요하며, lockfile은 배포되지 않고 생성되므로 새로 clone한 저장소에는 lockfile이 없습니다. 먼저 lockfile을 해석하여 생성하거나, 빌드가 채우도록 합니다:
aggrega pull --release release.yaml # resolve once, then build with no flagaggrega build --release release.yaml --auto-pull # or resolve during the build해석 과정에서는 gateway의 Recipe가 렌더링하는 APISIX chart를 해당 chart 자체의 저장소에서 가져와 고정하므로 네트워크가 필요합니다. 이 workspace는 .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>/distAI 어시스턴트 사용
Aggrega 도구로 설정한 AI 어시스턴트도 같은 작업을 할 수 있습니다. 다음 프롬프트를 붙여 넣으십시오.
Aggrega 도구만 사용하고 폴더를 직접 만들지 마십시오. 워크스페이스 폴더에 아직 `apisix-token-budget` 폴더가 없으면 `example`에 `apisix-token-budget`을 지정하고 `dir` 없이 `scaffold` 도구를 한 번 호출하십시오. 그러면 예제가 새 `apisix-token-budget` 폴더에 쓰입니다. 그런 다음 `workspace_root`에 `apisix-token-budget`, `release`에 `release.yaml`, `auto_pull`에 true, `write`에 true를 지정하여 `build` 도구를 호출하십시오. 빌드가 어떤 파일을 썼는지 알려 주십시오. 파일은 `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에 기록됩니다. 이 파일은 gateway가 마운트하여
전체 라우팅 구성을 읽어 들이는 ConfigMap입니다. 각 모델은 클러스터 내부 이름을 OpenAI의 API 호스트에 매핑하는
Service 파일 하나를 렌더링하며, 모델 연결의 각 자격 증명은
gateway와 연결의 별칭을 따라 이름 붙은 자체 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의 토큰 속도
제한인 ai-rate-limiting은 자신이 선언된 객체 아래에 카운트를 유지합니다. 각 라우트에
작성하면 라우트마다 카운트를 하나씩 유지하고, 모든 라우트가 service_id로 지정하는
model-budget에 한 번 작성하면 게이트웨이가 서비스하는 모든 것에 대해 카운트를 하나만
유지합니다. 이것이 연결이 요청한 gateway 범위입니다. scope: model을 사용하면 Recipe는
대신 연결마다 서비스 하나, 즉 model-assistant-budget과 model-summarizer-budget을 작성하므로
각 모델이 자체 한도를 갖습니다.
기간은 초 단위의 윈도입니다. 1d는 86400으로 작성됩니다. 윈도는
이전 윈도가 닫힌 뒤의 첫 모델 요청과 함께 열리고 그 시간 동안 지속되며,
자정에 시작하지 않습니다. 달력상의 한 달은 초 수가 고정되어 있지 않으므로,
아래와 같이 1mo는 거부됩니다.
단위는 무엇을 셀지를 나타냅니다. total_tokens는 각 모델의 응답이
읽기와 쓰기를 합쳐 보고하는 토큰이고, prompt_tokens와
completion_tokens는 한쪽만 셉니다. 게이트웨이는 응답이 보고하는 것을 셀 뿐
가격은 매기지 않으므로, 미국 달러 단위의 예산은 유지하지 않습니다.
각 모델에는 채팅 라우트가 있고 completion 라우트는 없습니다. 예산이 없으면
각 별칭은 /<alias>/v1/completions도 받습니다. APISIX는 프로토콜을 인식하는 요청에서만
응답의 토큰을 읽는데, 본문에 messages가 아닌 prompt를 담는 completion 요청은
그에 해당하지 않습니다. 이런 요청은 응답은 받지만 카운트되지 않습니다. 따라서 예산이
연결되어 있는 동안에는 해당 라우트가 작성되지 않으며, completion 요청에는 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는 차트를 하나로 고정합니다.
실행 시 게이트웨이가 하는 일
모델 요청이 들어올 때마다 게이트웨이는 카운트를 limit과 비교합니다. 카운트가 한도에 도달하면 게이트웨이는 윈도우가 닫힐 때까지 요청을 모델에 보내지 않고 503 Service Temporarily Unavailable로 응답합니다. 이 응답에는 게이트웨이 자체의 X-AI-RateLimit-Limit-…,
X-AI-RateLimit-Remaining-…, X-AI-RateLimit-Reset-… 헤더가 포함됩니다. 요청의
토큰은 응답이 완료될 때 더해지므로, 카운트를 한도에 이르게 하는 요청은 처리되며, 그와 함께 이미 진행 중인 요청도 처리됩니다.
여기서 두 가지 결과가 따르며, 둘 다 구성이 아니라 게이트웨이의 동작입니다:
- 재시작하면 새 윈도우가 시작됩니다. 카운트는 게이트웨이 프로세스의 메모리에 있으므로, 롤링되거나 재시작된 파드는 0부터 카운트를 시작합니다.
- 토큰을 보고하지 않는 응답은 아무것도 카운트하지 않습니다. 카운트는 각 모델이 보고하는 값입니다. 게이트웨이는 스트리밍 채팅 요청에 사용량을 보고하도록 요청하며, 아무것도 보고하지 않는 모델은 아무것도 더하지 않습니다.
빌드를 중단시키는 것
다음 각 경우에 빌드는 무엇을 바꿔야 하는지 알려 주는 문장을 출력합니다.
-
미국 달러 단위의 비용. 첨부에
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 assertionscaused 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, 그리고 토큰 수가 정수가 아닌 한도. -
게이트웨이에 대한 두 번째
core/period-budget첨부. 게이트웨이는 하나의 라우트에서 하나의 토큰 속도 제한만 실행합니다. -
models소켓에 아무것도 연결하지 않음, 이 경우 셀 모델 라우트가 남지 않습니다. 두 연결만 제거하면 게이트웨이 자체의 Component가 먼저 빌드를 중단하고, 모델이 없는 게이트웨이가 라우트를 유지하는 데 쓰는 etcd 저장소와 Admin API 키를 요구합니다. -
다른 구현. Manifest에서
core/gateway/apisix를helm/apisix에 매핑하면 빌드는models연결에서helm/apisix-chart를 지목하며 중단됩니다. 이 구현은 라우트를 etcd에 두고 APISIX 3.17.0을 실행하며, 라우트를 하나도 렌더링하지 않습니다. 예산 첨부에서도 빌드가 중단되는데, 이 구현에는 예산을 기록할 라우트가 없고, 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: 3600Manifest는 이미 이 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]여기에는 어떤 호출자의 키도 들어 있지 않습니다. 각 컨슈머는 caller_keys 연결이 렌더링하는 Secret에서
호출자 자신의 이름으로 Deployment가 채우는 변수를 지정하고,
이를 전체 헤더로 조합합니다:
- 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 소켓의 모든 연결과 마찬가지로 자체 라우트를 받습니다.
컴파일러가 해석하지 않는 부분
컴파일러는 한도, 기간, 단위를 문자열로 routes 파일에 전달하고, 각 모델의 엔드포인트와 모델 이름은 해당 모델이 게시하는 값에서 가져와 전달합니다. 컴파일러는 OpenAI에 접속하지 않고, 응답이 토큰 수를 보고하는지 알지 못하며, 스스로 아무것도 세지 않습니다. 위의 각 중단은 카탈로그 자체의 엔터티가 선언한 것으로, 예산이나 캐시의 구현 또는 게이트웨이의 다른 Recipe에 있는 assertion으로 선언되며, 그중 어느 것도 트래픽에 대한 이해에 기반하지 않습니다.
응용하기
- 모델별 한도.
scope: model을 설정합니다. 각 별칭은 자체 서비스와 자체 카운트를 갖습니다. - 호출자별 한도. 위의 “A semantic cache needs callers”에서처럼 Release에 호출자와 그 키를
선언하고
scope: caller를 설정합니다. 각 호출자는 모든 라우트에 걸쳐 자체 카운트를 갖습니다. - 한쪽만 세기. 모델이 읽는 양을 세려면
unit: prompt_tokens를 설정하고, 모델이 쓰는 양을 세려면completion_tokens를 설정합니다. - 더 짧거나 더 긴 윈도. Release에서
period를6h나30d처럼 초, 분, 시간 또는 일 단위의 수로 설정합니다.