LLM 비용 최적화
LLM 비용 최적화 (LLM Cost Optimization)
이 레시피는 Kong AI Gateway로 LLM 인프라 비용을 줄이는 네 가지 기법을 소개해요. 시맨틱 라우팅으로 충분한 수준의 가장 저렴한 모델에 요청을 보내고, 시맨틱 캐싱으로 중복 LLM 호출을 없애고, 프롬프트 압축으로 토큰 수를 줄이고, 비용 기반 레이트 리밋으로 Consumer 등급별 달러 예산을 강제해요. 다섯 개의 Kong 플러그인이 하나의 게이트웨이 엔드포인트에서 함께 동작하며, 애플리케이션 코드 변경 없이 모든 요청에 네 가지 기법이 적용돼요
출처: 문서
본문
개요
이 레시피는 네 가지 독립적이면서 조합 가능한 기법으로 LLM 인프라 비용을 줄이도록 Kong AI Gateway를 구성해요: 쿼리를 가장 저렴한 적정 모델로 보내는 시맨틱 라우팅, 중복된 LLM 호출을 완전히 없애는 시맨틱 캐싱, 프로바이더에 도달하기 전에 토큰 수를 줄이는 프롬프트 압축, 그리고 Consumer 등급별로 달러 예산을 강제하는 비용 기반 레이트 리밋이에요. 이 튜토리얼을 마치면 모든 요청에 네 가지 기법을 모두 적용하는 단일 게이트웨이 엔드포인트를 갖게 되고, 애플리케이션 코드 변경은 전혀 필요 없어요.
이 레시피는 다섯 개의 Kong 플러그인이 함께 동작해요: Consumer 식별을 위한 key-auth, 시맨틱 모델 라우팅을 위한 ai-proxy-advanced, 임베딩 기반 응답 캐싱을 위한 ai-semantic-cache, LLMLingua 기반 토큰 축소를 위한 ai-prompt-compressor, 그리고 Consumer Group별 비용 기반 예산 상한을 위한 ai-rate-limiting-advanced예요.
전제 조건
Kong Konnect
이 튜토리얼은 Kong Konnect를 사용해요. quickstart 스크립트를 통해 레시피 전용 Control Plane과 로컬 Data Plane을 프로비저닝하게 돼요.
-
Konnect PAT 페이지를 열고 Generate Token을 선택해 새 개인 액세스 토큰을 만드세요.
-
토큰을 내보내세요. 이 토큰은 나중에 kongctl 명령에서 다시 사용돼요:
export KONNECT_TOKEN='YOUR_KONNECT_PAT' -
레시피 전용 Control Plane 이름을 설정하고 quickstart 스크립트를 실행하세요:
export KONNECT_CONTROL_PLANE_NAME='llm-cost-optimization-recipe' curl -Ls https://get.konghq.com/quickstart | \ bash -s -- -k $KONNECT_TOKEN \ -e KONG_NGINX_WORKER_PROCESSES=1 \ --deck-output이 스크립트는
llm-cost-optimization-recipe라는 이름의 Konnect Control Plane과 여기에 연결된 로컬 Data Plane을 프로비저닝하고, 나머지 세션 변수에 해당하는export라인을 출력해요. 안내가 뜨면 그 내용을 셸에 붙여 넣으세요.
kongctl + decK
이 튜토리얼은 Kong 구성을 관리할 때 kongctl과 decK를 사용해요.
-
developer.konghq.com/kongctl에서 kongctl을 설치하세요.
-
docs.konghq.com/deck에서 decK 버전 1.43 이상을 설치하세요.
-
둘 다 설치됐는지 확인하세요:
kongctl version deck version
AI 자격 증명
라우팅할 프로바이더를 고르고 그 자격 증명을 내보내세요. 같은 자격 증명이 아래의 모든 apply 탭에서 재사용돼요.
OpenAI
이 튜토리얼은 OpenAI를 사용해요:
-
API 키로 decK 변수를 만드세요:
export DECK_OPENAI_TOKEN='Bearer sk-YOUR-KEY'
AWS Bedrock
이 튜토리얼은 AWS Bedrock을 사용해요:
-
사용하려는 챗 모델과 임베딩 모델 양쪽 모두에 Bedrock 모델 액세스가 활성화된 AWS 계정을 갖고 있는지 확인하세요.
-
AWS 자격 증명으로 decK 변수를 만드세요:
export DECK_AWS_ACCESS_KEY_ID='your-access-key' export DECK_AWS_SECRET_ACCESS_KEY='your-secret-key' export DECK_AWS_REGION='us-east-1'
Redis Stack
ai-semantic-cache 플러그인과 ai-proxy-advanced 플러그인은 캐시 조회와 시맨틱 라우팅 양쪽에서 벡터 데이터베이스로 Redis를 사용해요.
-
Redis Stack을 로컬에서 실행하세요:
docker run -d --name redis-stack -p 6379:6379 redis/redis-stack-server:latest -
플러그인이 Data Plane 컨테이너 안에서 연결할 수 있도록 Redis 호스트를 내보내세요:
export DECK_REDIS_HOST='host.docker.internal'
LLMLingua 프롬프트 압축기
ai-prompt-compressor 플러그인은 외부 LLMLingua 압축 서비스가 필요해요. Kong은 프라이빗 Cloudsmith 레지스트리에 호스팅된 Docker 이미지를 제공해요.
-
Kong 계정 팀이나 지원팀을 통해 레지스트리 자격 증명을 받으세요.
-
레지스트리에 로그인하세요:
docker login docker.cloudsmith.io -
압축 서비스를 시작하세요:
docker run -d \ --name llmlingua-compressor \ -p 8080:8080 \ -e LLMLINGUA_DEVICE_MAP=cpu \ --memory=2g \ docker.cloudsmith.io/kong/ai-compress/service:v0.0.3이 서비스는 최소 2 GB의 RAM이 필요해요. 개발에는 CPU로도 충분하고, GPU 기반 배포는 부하가 걸렸을 때 지연 시간을 개선해 줘요.
-
압축기 URL을 설정하세요:
export DECK_COMPRESSOR_URL='http://host.docker.internal:8080'
Python 3.11+
데모 스크립트에는 Python 3.11 이상이 필요해요. 격리된 환경을 설정하세요:
python3 -m venv .venv
source .venv/bin/activate
pip install 'openai>=1.0.0' 'tiktoken>=0.7.0'
문제 상황
LLM을 배포하는 대부분의 조직은 단일 모델 엔드포인트로 운영하면서 인프라 계층에는 비용 인텔리전스가 없어요. 이로 인해 서로 누적되는 여러 가지 비효율이 생겨요:
-
복잡도와 상관없이 모든 쿼리에 같은 모델이 쓰여요. "2+2는 얼마죠?" 같은 질문도 "분산 데이터베이스 아키텍처를 설계해 보세요."와 동일한 모델로 향해요. 저렴한 모델도 간단한 질문은 똑같이 잘 답하지만, 라우팅 로직이 없기 때문에 비싼 모델이 모든 요청을 받아요. 팀은 모든 요청에 프리미엄 모델을 써서 과지출을 하거나, 가장 저렴한 옵션을 기본으로 삼느라 복잡한 쿼리를 제대로 처리하지 못하거나 둘 중 하나예요.
-
의미상 동일한 질문이 LLM을 다시 호출해요. 다섯 명의 사용자가 "프랑스의 수도는 어디죠?"를 조금씩 다르게 표현해서 물으면, 다섯 번의 별도 LLM 호출과 다섯 개의 별도 청구서가 생겨요. 쿼리 표현이 서로 달라서 전통적인 정확 일치 캐싱으로는 해결되지 않아요. 임베딩 기반 시맨틱 비교는 이런 근접 중복을 잡아내지만, 이를 각 애플리케이션에 직접 넣으려면 서비스마다 벡터 데이터베이스와 임베딩 파이프라인,
-
사용자별 또는 등급별 예산 차등이 없어요. 게이트웨이 계층에서 Consumer 신원을 알 수 없으면 모든 사용자가 같은 제한을 공유해요. "무료 등급은 시간당 $10, 엔터프라이즈 등급은 시간당 $100"이라고 구분해 말할 방법이 없어요. 요청을 보내는 사람이 누구든 레이트 리밋은 똑같이 적용돼요.
근본적인 문제는 어떤 모델을 사용할지, 캐시할지 여부, 압축할지 여부, 예산을 얼마나 배정할지 같은 비용 최적화 결정이 인프라 계층에서 중앙적으로 강제되는 대신 각 애플리케이션 팀에 떠넘겨지고 있다는 점이에요.
해결 방법
Kong AI Gateway는 네 가지 비용 최적화 기법을 모두 프록시 계층에서 적용하며, 모든 요청에 투명하게 동작해요. 각 기법은 위의 문제 중 하나를 해결해요:
-
시맨틱 라우팅은 "모든 요청에 하나의 모델" 방식을 대체해요. Kong은 들어오는 각 프롬프트를 임베딩해서 벡터 데이터베이스의 타겟 설명과 비교해요. 단순한 쿼리(
CATCHALL타겟과 유사도가 높은 경우)는 저렴한 모델로 라우팅돼요. 복잡한 쿼리("상세한 추론" 타겟 설명과 일치하는 경우)는 프리미엄 모델로 라우팅돼요. 라우팅 결정은 자동으로 이뤄지며, 애플리케이션 로직도 관리해야 할 규칙도 필요 없어요. -
시맨틱 캐싱은 중복되는 LLM 호출을 없애요. 요청이 LLM에 도달하기 전에 Kong은 프롬프트를 임베딩하고 Redis에서 시맨틱하게 유사한 캐시된 응답을 검색해요. 유사도가 임계값을 넘으면 Kong은 토큰을 하나도 소비하지 않고 100ms 미만의 지연 시간으로 캐시된 응답을 즉시 반환해요. 캐시는 모든 사용자 전반에 걸쳐 동작하기 때문에, 한 사용자의 질문이 같은 것을 묻는 모든 사람에게 도움이 돼요.
-
프롬프트 압축은 청구되기 전에 토큰 수를 줄여요. Kong은 프롬프트를 LLMLingua 서비스에 통과시켜서 의미는 유지하면서 중복 토큰을 제거해요. 200토큰짜리 장황한 프롬프트가 120토큰짜리 압축된 프롬프트로 바뀌죠. LLM은 압축된 버전을 처리하고, 토큰 청구에는 더 작은 수가 반영돼요. 압축은 설정 가능한 임계값을 넘는 프롬프트에만 활성화돼요. 짧은 프롬프트는 그대로 통과해요.
-
비용 기반 레이트 리밋은 토큰 수가 아니라 달러 예산을 강제해요. Kong은 각 타겟에 설정된 모델별
input_cost와output_cost값을 사용해 각 응답의 실제 비용을 계산한 뒤, 그 비용을 Consumer의 예산에서 차감해요. 스탠다드 등급 사용자는 시간당 $10 예산을, 프리미엄 등급 사용자는 시간당 $100 예산을 받아요. 예산이 소진되면 Kong은429 Too Many Requests를 반환해서 예상치 못한 청구를 막아줘요.
sequenceDiagram
participant C as Client
participant K as Kong AI Gateway
participant LC as LLMLingua Compressor
participant L as LLM Provider
C->>K: POST /llm-cost-optimization (apikey, prompt)
activate K
K->>K: key-auth — Consumer → standard or premium tier
alt ai-semantic-cache: hit
K-->>C: Cached response (no LLM call)
else ai-semantic-cache: miss
K->>LC: ai-prompt-compressor — compress prompt
activate LC
LC-->>K: Compressed prompt
deactivate LC
K->>K: ai-proxy-advanced — embed query, route to cheap or expensive model by similarity
K->>L: Forwarded request
activate L
L-->>K: Native response
deactivate L
K->>K: ai-rate-limiting-advanced — deduct $cost from tier budget
K-->>C: OpenAI-format response (stored in semantic cache)
end
deactivate K
클라이언트 애플리케이션
책임: Consumer 등급을 식별하는 apikey 헤더와 함께 OpenAI 형식 채팅 요청을 보내요
Key Auth 플러그인
책임: API 키를 조회하고, 일치하는 Kong Consumer를 요청에 연결하고, 요청을 Consumer의 등급에 묶어요
AI Semantic Cache 플러그인
책임: 프롬프트를 임베딩하고, Redis에서 캐시된 응답을 검색하고, 캐시 히트 시 즉시 응답을 반환해요
AI Prompt Compressor 플러그인
책임: LLM에 도달하기 전에 LLMLingua를 통해 장황한 프롬프트를 압축해요
AI Proxy Advanced 플러그인
책임: 저렴한 모델 또는 고가 모델로 시맨틱 라우팅하고, 프로바이더 인증을 주입해요
AI Rate Limiting Advanced 플러그인
책임: 요청별 비용을 계산하고, Consumer Group별로 달러 기반 예산 상한을 강제해요
Redis Stack
책임: 시맨틱 캐싱과 시맨틱 라우팅 모두에 필요한 벡터 검색을 제공해요
LLMLingua 서비스
책임: 소형 언어 모델을 사용해 토큰 수준 프롬프트 압축을 수행해요
LLM 프로바이더
책임: 모델 추론을 수행해요 (저렴한 타겟과 고가 타겟)
동작 방식
Kong을 통과하는 요청은 인증, 캐시 확인, 프롬프트 압축, 모델로의 시맨틱 라우팅, 비용 기반 속도 제한이라는 다섯 단계로 처리돼요.
- 클라이언트가 자신의 티어의 정적 API 키를 담은
apikey헤더와 함께/llm-cost-optimization으로 챗 컴플리션 요청(OpenAI 형식)을 보내요. - Key Auth 플러그인이 등록된 Consumer 자격 증명을 대상으로 키를 조회해요. 키가 없거나 알 수 없으면 Kong이 업스트림 호출 전에
401로 즉시 중단해요. 일치하면 플러그인이 일치하는 Consumer(standard-user또는premium-user)를 요청에 연결하고, 이를 통해 나중에 어떤 Consumer Group의 속도 제한이 적용될지가 결정돼요. - AI Semantic Cache 플러그인이 최신 사용자 메시지를 임베딩하고, Redis에서 시맨틱하게 유사한 캐시된 응답을 검색해요. 히트하면(유사도가
0.8초과) Kong이 캐시된 응답을 즉시 반환하고 더 이상 플러그인이 실행되지 않아요. 미스하면 요청이 계속 진행돼요. - AI Prompt Compressor 플러그인이 설정된 토큰 임계값을 넘는 프롬프트를 LLMLingua 서비스로 보내고, 서비스는 중복 토큰을 제거한 압축 버전을 반환해요. 짧은 프롬프트는 그대로 통과해요.
- AI Proxy Advanced 플러그인이 프롬프트를 임베딩하고, 각 타겟의
description임베딩과 코사인 유사도를 계산해요. 가장 가까운 매치가 선택돼요. 그런 다음 플러그인이 클라이언트의apikey헤더를 제거하고, 업스트림 제공자의 자격 증명을 주입하며, (업스트림이 다른 형식을 사용하는 경우) OpenAI 형식 본문을 제공자의 네이티브 형식으로 변환해요. - Kong이 요청을 LLM 제공자의 API 엔드포인트로 전달하고, 응답을 OpenAI 형식으로 다시 정규화한 뒤, 이후에 유사한 프롬프트를 위해 시맨틱 캐시에 저장해요.
- AI Rate Limiting Advanced 플러그인이 토큰 수와 타겟의
input_cost/output_cost값을 바탕으로 응답의 달러 비용을 계산한 다음, 그 비용을 Consumer Group의 윈도우에서 차감해요. 응답 헤더에 남은 예산이 담겨 있어서 클라이언트가 자신의 지출을 모니터링할 수 있어요.
Key Auth: API 키 인증과 Consumer 매핑
Key Auth 플러그인은 체인의 맨 앞에 있으면서 모든 요청의 관문 역할을 해요. 각 Consumer는 keyauth_credentials 블록에 하나 이상의 API 키로 등록돼요. 요청이 도착하면 플러그인이 설정된 헤더(apikey)를 읽고, Kong의 Consumer 자격 증명 저장소에서 키를 조회한 뒤, 일치하는 Consumer를 요청에 연결해요. 매치된 Consumer가 바로 비용 속도 제한을 위해 요청을 Consumer Group에 묶는 요소예요. 두 Consumer(standard-user와 premium-user)는 두 Consumer Group(시간당 $10인 standard-tier, 시간당 $100인 premium-tier)에 속해요. 그래서 클라이언트가 보내는 API 키가 요청이 실행될 티어를 결정해요.
설정 세부 사항
- name: key-auth
config:
key_names:
- apikey
hide_credentials: true
{:.no-copy-code}
key_names: [apikey]. 플러그인이 API 키를 찾을 헤더(또는 쿼리 파라미터)예요. 레시피는 apikey를 사용해요. Key Auth 플러그인이 헤더 값에 대해 정확한 문자열 매치를 수행하고 Bearer 토큰을 위해 Authorization을 검사하지 않기 때문이에요. OpenAI SDK의 api_key 필드는 항상 Authorization: Bearer <key>로 직렬화되는데, Kong은 이를 리터럴 문자열 Bearer <key>로 읽어서 저장된 어떤 자격 증명과도 매치하지 못해요. 아래 "Try it out" 섹션은 SDK의 Bearer 토큰을 서버 측에서 apikey 헤더로 연결해 주는 pre-function 패턴을 가리켜요. Key Auth로 OpenAI SDK 클라이언트 인증하기 가이드에 전체 패턴이 나와 있어요.
hide_credentials: true. 업스트림으로 전달하기 전에 요청에서 API 키를 제거해요. 제공자는 Consumer의 API 키를 절대 볼 수 없어요. 이는 3.14의 기본값이지만, 레시피에서는 명확성을 위해, 그리고 이전 Gateway 버전에서도 동작하도록 이식성을 유지하기 위해 명시적으로 설정해요.
익명 폴백. 401을 반환하는 대신, 인증되지 않은 요청이 자체적으로 제한된 Consumer Group 예산을 가진 지정된 "anonymous" Consumer로 넘어가도록 anonymous: <consumer-id>를 설정해요. 공개/무료 티어 엔드포인트에 유용해요. 전체 옵션 목록은 key-auth 참조에서 확인하세요.
실제 IdP로 확장하기. 플랫폼이 (정적 API 키 대신) 최종 사용자 신원을 지원할 준비가 되면, key-auth를 openid-connect로 교체하고 JWT 클레임을 Consumer Group에 매핑해요. 애플리케이션 코드는 보내는 인증 헤더만 바꾸면 돼요. 이 레시피의 나머지 부분(시맨틱 캐시, 압축, ai-proxy-advanced, ai-rate-limiting-advanced)은 그대로 유지돼요. JWT 패턴은 basic-llm-routing 레시피를, 엔드투엔드 Okta 통합은 claude-code-sso 레시피를 확인하세요.
AI Semantic Cache: 임베딩 기반 응답 캐싱
AI Semantic Cache 플러그인은 요청이 LLM에 도달하기 전에 가로채서, 최신 사용자 메시지를 임베딩하고, Redis에서 시맨틱하게 유사한 질문에 대한 캐시된 응답을 검색해요. 매치하면 Kong이 캐시된 응답을 즉시 반환해요. 캐시는 모든 Consumer가 공유하기 때문에, 한 사용자의 질문이 나중에 비슷한 것을 묻는 모든 사용자에게 도움이 돼요. 기본 임계값은 충분히 보수적이어서, 의역된 중복 질문("What is machine learning?" vs "Explain machine learning to me")은 매치되는 반면, 주제는 관련 있지만 서로 다른 질문("What is the capital of France?" vs "What is the capital of Germany?")은 매치되지 않아요.
설정 세부 사항
- name: ai-semantic-cache
config:
cache_ttl: 300
message_countback: 1
stop_on_failure: false
embeddings:
auth:
header_name: Authorization
header_value: ${{ env "DECK_OPENAI_TOKEN" }}
model:
provider: openai
name: ${{ env "DECK_EMBEDDINGS_MODEL" }}
vectordb:
dimensions: ${{ env "DECK_EMBEDDINGS_DIMENSIONS" }}
distance_metric: cosine
strategy: redis
threshold: 0.3
redis:
host: ${{ env "DECK_REDIS_HOST" }}
port: 6379
{:.no-copy-code}
threshold: 0.3. 히트로 간주되기 위해 들어오는 프롬프트의 임베딩과 캐시된 프롬프트 간에 허용되는 최대 코사인 거리예요(낮을수록 엄격해요). text-embedding-3-small에서는 "What is machine learning?"과 "Explain machine learning to me" 같은 의역된 질문이 보통 0.20–0.28 거리에 위치하기 때문에, 0.3은 정당한 의역은 허용해요. 서로 다른 프롬프트(예: "Say hello" vs ML 질문)는 거리 ≥ 0.75에 위치해서 올바르게 제외돼요. 시맨틱하게 다른 프롬프트가 충돌하는 것이 보이면 0.2 쪽으로 조이세요. 더 폭넓은 재표현을 잡으려면 잘못된 캐시 히트의 위험을 감수하고 0.4 쪽으로 느슨하게 하세요.
cache_ttl: 300. 캐시된 응답은 5분(300초) 후에 만료돼요. 이는 비용 절감과 신선도 사이의 균형을 맞춰요. 자주 바뀌지 않는 사실 기반 쿼리라면 3600(1시간) 이상으로 늘리세요. 빠르게 변하는 데이터라면 줄이세요.
message_countback: 1. 캐시 조회 시 최신 사용자 메시지만 벡터화돼요. 앞선 메시지가 예상 응답을 바꾸는 중요한 컨텍스트를 제공하는 멀티턴 대화에서는 2나 3으로 설정하세요.
stop_on_failure: false. Redis에 도달할 수 없거나 임베딩 호출이 실패하면, 오류를 반환하는 대신 요청이 LLM으로 그대로 진행돼요. 캐시 레이어는 순수하게 추가적인 계층이며 요청을 절대 막지 않아요.
캐시 히트 시 Kong은 X-Cache-Status: Hit와 함께 저장된 응답을 반환하며 X-Kong-Upstream-Latency 헤더는 없어요(LLM 호출이 이루어지지 않았어요). 미스 시 요청은 다음 플러그인으로 계속 진행되고, Kong은 이후 요청을 위해 응답을 캐시해요.
캐시 히트는 모델에 구애받지 않아요. AI Semantic Cache 플러그인이 AI Proxy Advanced 플러그인 이전에 실행되기 때문에, 히트 시에는 라우팅 결정이 생략돼요. 캐시된 응답은 요청이 원래 선택했을 타겟이 어느 것이든 관계없이 반환돼요. 따라서 저렴한 모델로 라우팅될 간단한 의역된 쿼리가 원래 비싼 모델에서 생성된 캐시된 응답을 받을 수도 있고, 그 반대도 가능해요. 캐시 키는 프롬프트 임베딩만으로 구성되며, 모델 친화성은 전혀 없어요. 모델별 캐시가 필요하다면(예: gpt-4o-mini 요청에 gpt-4o 답변이 제공되는 것을 피하고 싶다면), 단일 공유 캐시에 의존하기보다 Route나 Consumer 기준으로 분할하세요.
AI Prompt Compressor: LLMLingua를 통한 토큰 축소
AI Prompt Compressor 플러그인은 프롬프트를, 시맨틱 의미를 보존하면서 중복 토큰을 제거하는 사이드카 LLMLingua 서비스로 보내요. LLM은 압축된 프롬프트를 처리하고, 청구 금액에는 더 작은 토큰 수가 반영돼요. 짧은 프롬프트는 압축의 이점이 없고 중요한 정보를 잃을 위험이 있기 때문에 그대로 통과해요.
설정 세부 사항
- name: ai-prompt-compressor
ordering:
before:
access:
- ai-proxy-advanced
config:
compressor_type: rate
compressor_url: ${{ env "DECK_COMPRESSOR_URL" }}
stop_on_error: false
compression_ranges:
- min_tokens: 100
max_tokens: 1000000
value: 0.6
{:.no-copy-code}
ordering.before.access: [ai-proxy-advanced]. 동적 플러그인 순서 지정을 사용해서 access 단계에서 ai-proxy-advanced보다 먼저 압축기를 실행해요. 압축기는 OpenAI 형식의 프롬프트를 대상으로 동작하기 때문에, ai-proxy-advanced보다 먼저 실행하면 프록시가 압축된 프롬프트를 받은 뒤에 제공자별 요청 변환을 처리한다는 것이 보장돼요. 이 레시피는 동일한 구성이 모든 제공자에서 동작하도록 순서를 명시적으로 설정해요.
compressor_type: rate. compression_ranges의 value는 보존 비율이에요. 0.6 값은 토큰의 60%를 보존한다는 뜻으로, 40% 감축이에요. 장황한 RAG 컨텍스트나 긴 시스템 프롬프트에는 공격적이지만 효과적이에요. 대안인 target_token 모드는 고정 토큰 수로 압축하는데, 특정 컨텍스트 윈도우 크기 이하를 보장해야 할 때 유용해요. 지원되는 압축기 유형의 전체 목록과 태그 기반 선택적 압축은 ai-prompt-compressor 참조에서 확인하세요.
compression_ranges. min_tokens와 max_tokens 사이에 있는 프롬프트만 압축돼요. 서로 다른 보존 비율을 가진 여러 범위를 정의할 수 있어서, 중간 길이 프롬프트는 가벼운 압축을, 긴 프롬프트는 공격적인 압축을 받도록 할 수 있어요.
stop_on_error: false. LLMLingua 서비스에 도달할 수 없으면, 압축되지 않은 프롬프트가 LLM으로 전달돼요. 캐시와 마찬가지로 압축도 순수하게 추가적인 계층이에요.
압축 왕복은 지연 시간을 추가해요(CPU 하드웨어에서는 수백 밀리초). 이는 X-Kong-Proxy-Latency에 나타나요. 지연 시간에 민감한 워크로드라면 GPU 기반 LLMLingua 배포를 고려해 보세요.
AI Proxy Advanced: 시맨틱 모델 라우팅과 제공자 변환
AI Proxy Advanced 플러그인은 모델 선택 결정부터 업스트림 호출까지 모든 것을 처리해요. 레시피는 두 개의 타겟을 구성하며, 각 타겟은 자신이 처리해야 할 쿼리 유형을 담은 description 필드를 가져요. 요청이 도착하면 플러그인이 프롬프트를 임베딩하고, 각 타겟의 설명 임베딩(Redis에 저장되어 있음)과 코사인 유사도를 계산한 다음, 가장 가까운 매치로 라우팅해요. CATCHALL 타겟은 단순하거나 주제에서 벗어난 쿼리를 처리하고, "detailed reasoning" 타겟은 프리미엄 모델이 필요한 복잡한 작업을 처리해요.
구성 세부 사항
- name: ai-proxy-advanced
config:
max_request_body_size: 10485760
response_streaming: allow
balancer:
algorithm: semantic
embeddings:
auth:
header_name: Authorization
header_value: ${{ env "DECK_OPENAI_TOKEN" }}
model:
provider: openai
name: ${{ env "DECK_EMBEDDINGS_MODEL" }}
vectordb:
dimensions: ${{ env "DECK_EMBEDDINGS_DIMENSIONS" }}
distance_metric: cosine
strategy: redis
threshold: ${{ env "DECK_PROXY_THRESHOLD" }}
redis:
host: ${{ env "DECK_REDIS_HOST" }}
port: 6379
targets:
- route_type: llm/v1/chat
description: CATCHALL
model:
model_alias: auto
name: ${{ env "DECK_CHAT_MODEL_1" }}
options:
input_cost: ${{ env "DECK_INPUT_COST_1" }}
output_cost: ${{ env "DECK_OUTPUT_COST_1" }}
- route_type: llm/v1/chat
description: Software architecture, system design, and complex code generation.
model:
model_alias: auto
name: ${{ env "DECK_CHAT_MODEL_2" }}
options:
input_cost: ${{ env "DECK_INPUT_COST_2" }}
output_cost: ${{ env "DECK_OUTPUT_COST_2" }}
{: .no-copy-code .collapsible }
balancer.algorithm: semantic. 시맨틱 유사도를 라우팅 전략으로 선택해요. 플러그인이 프롬프트를 임베딩하고, 각 타깃의 description 임베딩과 코사인 유사도를 계산해서, 임계값을 넘는 타깃 중 유사도가 가장 높은 곳으로 라우팅해요. 다른 밸런싱 알고리즘(round-robin, lowest-latency, lowest-usage, priority)은 ai-proxy-advanced 참조 문서에 정리되어 있어요.
threshold (환경 변수 DECK_PROXY_THRESHOLD). 들어오는 프롬프트의 임베딩과 타깃의 description 임베딩 사이 코사인 거리의 최댓값으로, 이 값 이하일 때 해당 타깃이 후보가 돼요 (낮을수록 엄격하고, AI Semantic Cache Plugin과 같은 규약이에요). 적절한 값은 어떤 임베딩 모델을 쓰는지에 따라 달라져요. 같은 콘텐츠라도 모델마다 절대 거리 스케일이 달라요. 이 레시피는 OpenAI의 text-embedding-3-small에는 0.75, Bedrock의 amazon.titan-embed-text-v2:0에는 0.85를 기본값으로 제공해요. 두 값 모두 데모 프롬프트를 기준으로 측정한 것이라, COMPLEX 프롬프트는 비싼 타깃으로 라우팅되고 단순한 프롬프트는 CATCHALL로 떨어져요. 임베딩 모델을 바꾸면 재조정이 필요하다고 보세요. 대표적인 프롬프트에서 각 타깃 설명까지의 코사인 거리를 측정하고, 정상 매치 거리보다는 높고 오탐 구간보다는 낮은 값을 고르세요.
model.model_alias: auto. 두 타깃이 같은 별칭을 공유하기 때문에, 클라이언트는 하나의 고정된 model 값("auto")만 보내고 업스트림 모델 선택은 Kong에 맡길 수 있어요. 별칭이 없으면 플러그인이 요청의 model 필드와 타깃에 설정된 model.name 사이의 엄격한 일치를 강제하고, 일치하지 않으면 400으로 거부해요. 모든 타깃에 동일한 별칭이 있으면 별칭 매칭이 모든 타깃을 통과시키고, 설정된 balancer.algorithm(여기서는 semantic)이 최종 선택을 해요.
description: CATCHALL. 이 타깃을 폴백으로 지정해요. 다른 어떤 타깃의 유사도 임계값도 넘지 못한 단순하거나 일반적이거나 주제에서 벗어난 쿼리가 여기로 떨어져요. 여기에 가장 저렴한 모델을 연결하세요.
description: "Software architecture, system design, and complex code generation.". 짧은 앵커 문구는 긴 산문보다 더 선명한 임베딩을 만들어요. 센트로이드가 여러 개념에 걸쳐 평균 내는 대신 한 곳에 집중되거든요. 프리미엄 모델이 필요한 쿼리 유형을 담은 하나의 간결한 문구로 다듬으세요. 여러 문장으로 된 설명은 피하세요. 유사도 점수가 희석되어 주제에 맞는 프롬프트까지 CATCHALL로 라우팅될 수 있어요.
**input_cost**와 output_cost. 100만 토큰당 비용이며, 달러 단위예요. 이 값들은 AI Rate Limiting Advanced Plugin이 각 요청의 실제 달러 비용을 계산할 때 사용해요. 프로바이더의 현재 가격에 맞게 설정하세요. 비용 공식은 다음과 같아요: cost = (prompt_tokens x input_cost + completion_tokens x output_cost) / 1,000,000.
**max_request_body_size**와 response_streaming. 레시피는 10 MB 요청 제한(일반적인 대화 컨텍스트와 적당한 RAG 주입에는 충분한 크기)을 설정하고 스트리밍 응답을 허용해요. 예상 워크로드에 맞게 두 값을 모두 조이거나 느슨하게 하세요.
이 레시피는 기본값인 llm_format: openai를 사용해요. 이 형식은 OpenAI 형식 요청을 받아들이고 프로바이더 응답을 다시 OpenAI 형식으로 정규화해요. 프로바이더 SDK를 사용하는 코드가 이미 있다면, llm_format을 해당 프로바이더의 네이티브 형식으로 설정해서 변환 없이 요청을 그대로 통과시킬 수 있어요. 지원되는 네이티브 형식은 ai-proxy-advanced 참조 문서를 확인하세요.
AI Rate Limiting Advanced: 달러 기반 예산 상한
AI Rate Limiting Advanced Plugin은 Consumer Group별로 달러 기반 예산 상한을 적용해요. 각
Consumer Group은 서로 다른 limit을 가진 자체 플러그인 인스턴스를 가져요. 예산이
달러로 표현되고 AI Proxy Advanced 타깃의 비용 값으로 계산되기 때문에, 시간당 $10 예산은
비싼 모델보다 저렴한 모델에서 훨씬 오래 가요. 비용 최적화에 딱 맞는 인센티브 구조예요.
구성 세부 사항
consumer_groups:
- name: standard-tier
plugins:
- name: ai-rate-limiting-advanced
config:
tokens_count_strategy: cost
llm_providers:
- name: openai
limit:
- 1
window_size:
- 3600
window_type: sliding
strategy: local
- name: premium-tier
plugins:
- name: ai-rate-limiting-advanced
config:
tokens_count_strategy: cost
llm_providers:
- name: openai
limit:
- 5
window_size:
- 3600
window_type: sliding
strategy: local
{:.no-copy-code}
tokens_count_strategy: cost. 원시 토큰을 세는 대신, Kong이 요청을 처리한 AI Proxy Advanced 타깃의 input_cost와 output_cost 값을 사용해 각 응답의 달러 비용을 계산해요. 카운팅 전략 전체 목록(요청 수, 프롬프트 토큰, 컴플리션 토큰, 총 토큰, 비용)은 ai-rate-limiting-advanced 참조 문서를 확인하세요.
**limit: [1]**과 limit: [5]. 윈도우당 달러 금액이에요. 스탠다드 티어는 시간당 $1, 프리미엄은 시간당 $5를 받아요. 레시피는 작은 예산을 사용해서 데모를 한 번만 실행해도 두 티어 모두에서 눈에 띄는 차감이 생겨요. 프로덕션 한도는 보통 훨씬 높아요 (예: 스탠다드 [10] / 프리미엄 [100]). 같은 프로바이더에 대해 여러 윈도우를 정의할 수도 있어요. 예를 들어 limit: [0.25, 1]에 window_size: [60, 3600]을 조합하면 분당 $0.25 그리고 시간당 $1로 지출이 제한돼요.
비용은 다음 요청에 반영돼요. 레이트 리미팅 플러그인은 LLM 응답으로부터 비용을 계산하기 때문에, 요청의 비용은 다음 요청에서 차감돼요. 현재 요청은 항상 완료돼요. 한도는 요청이 전송되기 전에 확인돼요.
window_type: sliding. 현재 윈도우를 평가할 때 이전 윈도우의 비율을 고려하는 슬라이딩 윈도우를 사용해요. 윈도우 경계에서의 버스트 지출을 막아 줘요. 더 단순한 버킷 기반 제한에는 fixed를 사용하세요.
strategy: local. 카운터는 각 노드의 Kong 인메모리 딕셔너리에 저장돼요. 멀티 노드 배포에서는 redis를 사용해 노드 간에 카운터를 공유하고, 비용 값이 소수이기 때문에 decrease_by_fractions_in_redis: true로 설정하세요.
Kong이 모든 요청에 응답 헤더를 설정해서 클라이언트가 남은 예산을 추적할 수 있어요: X-AI-RateLimit-Limit-hour-openai: 1과 X-AI-RateLimit-Remaining-hour-openai: 0.987. 예산이 소진되면 Kong이 Retry-After 헤더와 함께 429 Too Many Requests를 반환해요. 헤더의 윈도우 라벨(hour, minute 등)은 설정된 window_size에서 파생돼요. 3600은 hour가 되고, 60은 minute가 되며, 표준이 아닌 크기는 초 값을 그대로 사용해요. 레시피의 두 타깃 모두 name: openai를 사용하기 때문에, 하나의 버킷이 gpt-4o와 gpt-4o-mini 전체의 티어 지출을 함께 추적해요. 모델별로 예산을 나누려면 서로 다른 name 값을 가진 별도의 llm_providers 항목을 추가하거나, 각 모델을 자체 Route로 분리하세요.
단순함을 위해 이 레시피는 Consumer API 키를 플러그인 구성에 직접 저장하고, 프로바이더 자격 증명은 환경 변수에 저장해요. 프로덕션에서는 대신 둘 다 Kong Vaults를 통해 참조하고, 선호하는 시크릿 매니저(AWS Secrets Manager, HashiCorp Vault, GCP Secret Manager, Azure Key Vault)를 백엔드로 사용하세요.
응답 예시
동일한 OpenAI 형식 요청이 Kong을 통과해요. 헤더가 각 플러그인 계층이 한 일을 증명해 줘요.
시맨틱 라우팅이 어떤 모델을 선택했는지(X-Kong-LLM-Model), 캐시가 응답을 제공했는지
(X-Cache-Status), 예산이 얼마나 남았는지(X-AI-RateLimit-Remaining-hour-*) 말이에요.
요청 본문 (단순한 사실 질문):
{
"messages": [{ "role": "user", "content": "What is the capital of France?" }]
}
{:.no-copy-code}
첫 번째 호출의 응답 헤더 (캐시 미스, 저렴한 모델로 라우팅됨):
HTTP/1.1 200 OK
X-Kong-LLM-Model: openai/gpt-4o-mini
X-Cache-Status: Miss
X-AI-RateLimit-Limit-hour-openai: 10
X-AI-RateLimit-Remaining-hour-openai: 9.999
X-Kong-Upstream-Latency: 845
X-Kong-Proxy-Latency: 120
{:.no-copy-code}
의역한 후속 호출의 응답 헤더 (캐시 히트, 업스트림 호출 없음):
HTTP/1.1 200 OK
X-Cache-Status: Hit
X-Kong-Proxy-Latency: 45
X-AI-RateLimit-Remaining-hour-openai: 9.999
{:.no-copy-code}
Kong이 다음 응답 헤더를 추가해요:
X-Kong-LLM-Model
설명: 요청을 처리한 업스트림 모델. 프로바이더 이름이 접두사로 붙고 시맨틱 라우팅으로 결정돼요
X-Cache-Status
설명: Hit 또는 Miss. 히트면 업스트림 LLM 호출이 이루어지지 않았어요
X-AI-RateLimit-Limit-hour-<provider>
설명: 이 Consumer 티어의 1시간 윈도우당 달러 예산 (윈도우 라벨은 window_size: 3600에서 파생)
X-AI-RateLimit-Remaining-hour-<provider>
설명: 현재 윈도우에 남은 달러 금액. 완료된 모든 요청의 비용이 반영돼요
X-Kong-Upstream-Latency
설명: Kong이 프로바이더의 응답을 기다린 시간 (ms). 캐시 히트에서는 없어요 (업스트림 호출 없음)
X-Kong-Proxy-Latency
설명: Kong이 요청을 처리하는 데 걸린 시간 (ms). 임베딩 조회와 압축 왕복이 포함돼요
Kong은 업스트림 요청에 X-Consumer-Username을 붙이지만 (LLM 프로바이더가 누가 호출하는지 볼 수 있도록), 다운스트림 클라이언트에게는 다시 돌려보내지 않아요. Consumer별 귀속 정보는 Konnect의 애널리틱스 뷰에 나타나요. 아래의 "Konnect에서 탐색하기"를 확인하세요.
Kong 구성 적용하기
아래 구성은 /llm-cost-optimization 경로에 Kong Gateway Service와 Route를 만들고,
apikey 헤더로 Consumer를 식별하기 위해 key-auth 플러그인을 연결한 다음,
캐시, 압축, 라우팅을 위해 ai-semantic-cache,
ai-prompt-compressor, 그리고
ai-proxy-advanced를 체이닝해요. 두 개의
Consumer Group(standard-tier와 premium-tier)이 각각 서로 다른 달러
예산을 가진 ai-rate-limiting-advanced 플러그인을 담고 있어요. 모든 리소스는 select_tags와 kongctl namespace로 스코핑되어서
나중에 깔끔하게 정리할 수 있어요. 연합 구성 관리에 대해 더 알아보려면
kongctl 문서를 확인하세요.
먼저, 아래의 apply 명령이 관리할 수 있도록 퀵스타트 Control Plane을 kongctl 네임스페이스로 adopt하세요:
kongctl adopt control-plane "${KONNECT_CONTROL_PLANE_NAME}" \
--namespace "${KONNECT_CONTROL_PLANE_NAME}" \
--pat "${KONNECT_TOKEN}"
Adopt를 하면 Control Plane에 KONGCTL-namespace 라벨이 표시돼요.
프로바이더 자격 증명, Redis 호스트, 컴프레서 URL은 사전 준비(Prerequisites) 단계에서 한 번 내보내져요. 아래의 각 탭은 프로바이더별 모델 및 비용 환경 변수만 설정하고 apply를 실행해요.
OpenAI
프로바이더별 환경 변수를 내보내세요:
export DECK_CHAT_MODEL_1='gpt-4o-mini' # cheap: general queries
export DECK_CHAT_MODEL_2='gpt-4o' # expensive: complex tasks
export DECK_INPUT_COST_1='0.15' # gpt-4o-mini: $0.15 per 1M input tokens
export DECK_OUTPUT_COST_1='0.60' # gpt-4o-mini: $0.60 per 1M output tokens
export DECK_INPUT_COST_2='2.50' # gpt-4o: $2.50 per 1M input tokens
export DECK_OUTPUT_COST_2='10.00' # gpt-4o: $10.00 per 1M output tokens
export DECK_EMBEDDINGS_MODEL='text-embedding-3-small'
export DECK_EMBEDDINGS_DIMENSIONS='1536'
export DECK_PROXY_THRESHOLD='0.75' # max cosine distance, tuned for text-embedding-3-small
Kong 구성을 적용하세요:
cat <<'EOF' > kong-recipe.yaml
_format_version: '3.0'
_info:
select_tags:
- llm-cost-optimization-recipe
services:
- name: llm-cost-optimization
url: http://localhost
routes:
- name: llm-cost-optimization
paths:
- /llm-cost-optimization
protocols:
- http
- https
methods:
- POST
- OPTIONS
strip_path: true
plugins:
- name: key-auth
instance_name: llm-cost-optimization-auth
config:
key_names:
- apikey
hide_credentials: true
- name: ai-semantic-cache
instance_name: llm-cost-optimization-cache
config:
cache_ttl: 300
message_countback: 1
stop_on_failure: false
embeddings:
auth:
header_name: Authorization
header_value: ${{ env "DECK_OPENAI_TOKEN" }}
model:
provider: openai
name: ${{ env "DECK_EMBEDDINGS_MODEL" }}
vectordb:
dimensions: ${{ env "DECK_EMBEDDINGS_DIMENSIONS" }}
distance_metric: cosine
strategy: redis
threshold: 0.3
redis:
host: ${{ env "DECK_REDIS_HOST" }}
port: 6379
- name: ai-prompt-compressor
instance_name: llm-cost-optimization-compressor
ordering:
before:
access:
- ai-proxy-advanced
config:
compressor_type: rate
compressor_url: ${{ env "DECK_COMPRESSOR_URL" }}
stop_on_error: false
compression_ranges:
- min_tokens: 100
max_tokens: 1000000
value: 0.6
- name: ai-proxy-advanced
instance_name: llm-cost-optimization-proxy
config:
max_request_body_size: 10485760
response_streaming: allow
balancer:
algorithm: semantic
embeddings:
auth:
header_name: Authorization
header_value: ${{ env "DECK_OPENAI_TOKEN" }}
model:
provider: openai
name: ${{ env "DECK_EMBEDDINGS_MODEL" }}
vectordb:
dimensions: ${{ env "DECK_EMBEDDINGS_DIMENSIONS" }}
distance_metric: cosine
strategy: redis
threshold: ${{ env "DECK_PROXY_THRESHOLD" }}
redis:
host: ${{ env "DECK_REDIS_HOST" }}
port: 6379
targets:
- route_type: llm/v1/chat
description: CATCHALL
auth:
header_name: Authorization
header_value: ${{ env "DECK_OPENAI_TOKEN" }}
model:
model_alias: auto
provider: openai
name: ${{ env "DECK_CHAT_MODEL_1" }}
options:
input_cost: ${{ env "DECK_INPUT_COST_1" }}
output_cost: ${{ env "DECK_OUTPUT_COST_1" }}
logging:
log_payloads: true
log_statistics: true
- route_type: llm/v1/chat
description: Software architecture, system design, and complex code generation.
auth:
header_name: Authorization
header_value: ${{ env "DECK_OPENAI_TOKEN" }}
model:
model_alias: auto
provider: openai
name: ${{ env "DECK_CHAT_MODEL_2" }}
options:
input_cost: ${{ env "DECK_INPUT_COST_2" }}
output_cost: ${{ env "DECK_OUTPUT_COST_2" }}
logging:
log_payloads: true
log_statistics: true
consumers:
- username: standard-user
keyauth_credentials:
- key: standard-api-key
- username: premium-user
keyauth_credentials:
- key: premium-api-key
consumer_groups:
- name: standard-tier
consumers:
- username: standard-user
plugins:
- name: ai-rate-limiting-advanced
config:
tokens_count_strategy: cost
llm_providers:
- name: openai
limit:
- 1
window_size:
- 3600
window_type: sliding
strategy: local
- name: premium-tier
consumers:
- username: premium-user
plugins:
- name: ai-rate-limiting-advanced
config:
tokens_count_strategy: cost
llm_providers:
- name: openai
limit:
- 5
window_size:
- 3600
window_type: sliding
strategy: local
EOF
echo "
_defaults:
kongctl:
namespace: llm-cost-optimization-recipe
control_planes:
- ref: recipe-cp
name: \"${KONNECT_CONTROL_PLANE_NAME}\"
_deck:
files:
- kong-recipe.yaml
" | kongctl apply -f - -o text --auto-approve --pat "${KONNECT_TOKEN}"
rm -f kong-recipe.yaml
{: data-test-step="block" .collapsible }
AWS Bedrock
프로바이더별 환경 변수를 내보내세요:
export DECK_CHAT_MODEL_1='amazon.nova-lite-v1:0' # cheap: general queries
export DECK_CHAT_MODEL_2='global.anthropic.claude-sonnet-4-5-20250929-v1:0' # expensive: complex tasks (uses cross-region inference profile — required for Claude 4.5)
export DECK_INPUT_COST_1='0.06' # Nova Lite: $0.06 per 1M input tokens
export DECK_OUTPUT_COST_1='0.24' # Nova Lite: $0.24 per 1M output tokens
export DECK_INPUT_COST_2='3.00' # Claude Sonnet: $3.00 per 1M input tokens
export DECK_OUTPUT_COST_2='15.00' # Claude Sonnet: $15.00 per 1M output tokens
export DECK_EMBEDDINGS_MODEL='amazon.titan-embed-text-v2:0'
export DECK_EMBEDDINGS_DIMENSIONS='1024'
export DECK_PROXY_THRESHOLD='0.85' # max cosine distance, tuned for amazon.titan-embed-text-v2:0
Kong 구성을 적용하세요:
cat <<'EOF' > kong-recipe.yaml
_format_version: '3.0'
_info:
select_tags:
- llm-cost-optimization-recipe
services:
- name: llm-cost-optimization
url: http://localhost
routes:
- name: llm-cost-optimization
paths:
- /llm-cost-optimization
protocols:
- http
- https
methods:
- POST
- OPTIONS
strip_path: true
plugins:
- name: key-auth
instance_name: llm-cost-optimization-auth
config:
key_names:
- apikey
hide_credentials: true
- name: ai-semantic-cache
instance_name: llm-cost-optimization-cache
config:
cache_ttl: 300
message_countback: 1
stop_on_failure: false
embeddings:
auth:
aws_access_key_id: ${{ env "DECK_AWS_ACCESS_KEY_ID" }}
aws_secret_access_key: ${{ env "DECK_AWS_SECRET_ACCESS_KEY" }}
model:
provider: bedrock
name: ${{ env "DECK_EMBEDDINGS_MODEL" }}
options:
bedrock:
aws_region: ${{ env "DECK_AWS_REGION" }}
vectordb:
dimensions: ${{ env "DECK_EMBEDDINGS_DIMENSIONS" }}
distance_metric: cosine
strategy: redis
threshold: 0.3
redis:
host: ${{ env "DECK_REDIS_HOST" }}
port: 6379
- name: ai-prompt-compressor
instance_name: llm-cost-optimization-compressor
ordering:
before:
access:
- ai-proxy-advanced
config:
compressor_type: rate
compressor_url: ${{ env "DECK_COMPRESSOR_URL" }}
stop_on_error: false
compression_ranges:
- min_tokens: 100
max_tokens: 1000000
value: 0.6
- name: ai-proxy-advanced
instance_name: llm-cost-optimization-proxy
config:
max_request_body_size: 10485760
response_streaming: allow
balancer:
algorithm: semantic
embeddings:
auth:
aws_access_key_id: ${{ env "DECK_AWS_ACCESS_KEY_ID" }}
aws_secret_access_key: ${{ env "DECK_AWS_SECRET_ACCESS_KEY" }}
model:
provider: bedrock
name: ${{ env "DECK_EMBEDDINGS_MODEL" }}
options:
bedrock:
aws_region: ${{ env "DECK_AWS_REGION" }}
vectordb:
dimensions: ${{ env "DECK_EMBEDDINGS_DIMENSIONS" }}
distance_metric: cosine
strategy: redis
threshold: ${{ env "DECK_PROXY_THRESHOLD" }}
redis:
host: ${{ env "DECK_REDIS_HOST" }}
port: 6379
targets:
- route_type: llm/v1/chat
description: CATCHALL
auth:
aws_access_key_id: ${{ env "DECK_AWS_ACCESS_KEY_ID" }}
aws_secret_access_key: ${{ env "DECK_AWS_SECRET_ACCESS_KEY" }}
model:
model_alias: auto
provider: bedrock
name: ${{ env "DECK_CHAT_MODEL_1" }}
options:
bedrock:
aws_region: ${{ env "DECK_AWS_REGION" }}
input_cost: ${{ env "DECK_INPUT_COST_1" }}
output_cost: ${{ env "DECK_OUTPUT_COST_1" }}
logging:
log_payloads: true
log_statistics: true
- route_type: llm/v1/chat
description: Software architecture, system design, and complex code generation.
auth:
aws_access_key_id: ${{ env "DECK_AWS_ACCESS_KEY_ID" }}
aws_secret_access_key: ${{ env "DECK_AWS_SECRET_ACCESS_KEY" }}
model:
model_alias: auto
provider: bedrock
name: ${{ env "DECK_CHAT_MODEL_2" }}
options:
bedrock:
aws_region: ${{ env "DECK_AWS_REGION" }}
input_cost: ${{ env "DECK_INPUT_COST_2" }}
output_cost: ${{ env "DECK_OUTPUT_COST_2" }}
logging:
log_payloads: true
log_statistics: true
consumers:
- username: standard-user
keyauth_credentials:
- key: standard-api-key
- username: premium-user
keyauth_credentials:
- key: premium-api-key
consumer_groups:
- name: standard-tier
consumers:
- username: standard-user
plugins:
- name: ai-rate-limiting-advanced
config:
tokens_count_strategy: cost
llm_providers:
- name: bedrock
limit:
- 1
window_size:
- 3600
window_type: sliding
strategy: local
- name: premium-tier
consumers:
- username: premium-user
plugins:
- name: ai-rate-limiting-advanced
config:
tokens_count_strategy: cost
llm_providers:
- name: bedrock
limit:
- 5
window_size:
- 3600
window_type: sliding
strategy: local
EOF
echo "
_defaults:
kongctl:
namespace: llm-cost-optimization-recipe
control_planes:
- ref: recipe-cp
name: \"${KONNECT_CONTROL_PLANE_NAME}\"
_deck:
files:
- kong-recipe.yaml
" | kongctl apply -f - -o text --auto-approve --pat "${KONNECT_TOKEN}"
rm -f kong-recipe.yaml
{: data-test-step="block" .collapsible }
직접 사용해 보기
데모 스크립트는 다섯 개의 Plugin을 순서대로 모두 실행해요. 시맨틱 라우팅을 시연하는 단순 쿼리와 복잡한 쿼리, 캐시 히트를 유발하는 바꿔 말한 후속 질문, 압축이 실제로 작동하는 모습을 보여 주는 장황한 프롬프트, 레이트 리밋 예산을 비교하려고 두 티어에서 동시에 보내는 병렬 호출, 그리고 업스트림 호출 전에 Kong가 미승인 요청을 거부하는지 확인하는 마지막 잘못된 API 키 호출이에요.
데모는
default_headers를 통해 API 키를 전달해요. OpenAI SDK가api_key를Authorization: Bearer헤더 용도로 예약해 두기 때문이에요. 클라이언트가api_key로 키를 직접 전달할 수 있게 하려면, Bearer 토큰을 서버 측에서apikey헤더로 복사하는 pre-function Plugin을 붙이세요. 이 패턴은 Authenticate OpenAI SDK clients with Key Auth 문서를 참고하세요.
데모 스크립트를 만드세요:
cat <<'EOF' > demo.py
"""LLM cost optimization demo. See README for context."""
import os
import sys
import time
from openai import APIStatusError, OpenAI
try:
import tiktoken
_ENC = tiktoken.encoding_for_model("gpt-4o")
except Exception:
_ENC = None
PROXY_URL = os.getenv("PROXY_URL", "http://localhost:8000")
CHAT_MODEL = "auto" # shared model_alias on both ai-proxy-advanced targets
BASE_URL = f"{PROXY_URL}/llm-cost-optimization"
# ANSI color codes. Disabled when stdout isn't a TTY or NO_COLOR is set.
_USE_COLOR = sys.stdout.isatty() and "NO_COLOR" not in os.environ
def _c(code: str, s: str) -> str:
return f"\033[{code}m{s}\033[0m" if _USE_COLOR else s
BOLD = lambda s: _c("1", s)
DIM = lambda s: _c("2", s)
GREEN = lambda s: _c("32", s)
YELLOW = lambda s: _c("33", s)
BLUE = lambda s: _c("34", s)
CYAN = lambda s: _c("36", s)
RED = lambda s: _c("31", s)
MAGENTA= lambda s: _c("35", s)
def make_client(api_key: str) -> OpenAI:
"""Construct an OpenAI client that sends the given API key in the apikey header."""
return OpenAI(
base_url=BASE_URL,
api_key="unused", # required by the SDK; Kong reads the apikey header instead
default_headers={"apikey": api_key},
)
standard_client = make_client("standard-api-key")
premium_client = make_client("premium-api-key")
def chat(client: OpenAI, prompt: str, label: str = "", original_tokens: int | None = None,
max_tokens: int = 250) -> float:
"""Send a chat request and print response details with Kong headers.
`max_tokens` caps the LLM's response length so the demo runs quickly. The full
answer doesn't matter for the demonstration; what matters is which model served
it, whether the cache hit, and the resulting token / cost accounting.
"""
start = time.time()
try:
response = client.chat.completions.with_raw_response.create(
model=CHAT_MODEL,
messages=[{"role": "user", "content": prompt}],
max_tokens=max_tokens,
)
except APIStatusError as e:
elapsed = time.time() - start
status = RED(BOLD(f"{e.status_code}"))
print(f"\n [{BOLD(label)}] {status} {e.message} ({elapsed:.2f}s)")
return elapsed
elapsed = time.time() - start
completion = response.parse()
h = response.headers
model = h.get("x-kong-llm-model", "(served from cache)")
cache = h.get("x-cache-status", ".")
upstream = h.get("x-kong-upstream-latency")
text = (completion.choices[0].message.content or "")[:120]
usage = completion.usage
if upstream and upstream != "0":
latency_extra = f"upstream: {upstream}ms"
else:
latency_extra = "cache hit, no upstream call"
short = prompt[:70] + ("..." if len(prompt) > 70 else "")
cache_color = GREEN if cache.lower() == "hit" else YELLOW
print(f"\n [{BOLD(label)}] '{short}'")
print(f" Model: {CYAN(BOLD(model))}")
print(f" Cache: {cache_color(BOLD(cache))}")
if original_tokens is not None and original_tokens > 0:
reduction_pct = 100 * (original_tokens - usage.prompt_tokens) / original_tokens
# Highlight the reduction — that's the headline of this section.
print(f" Tokens: pre-compression~{original_tokens} -> "
f"billed={MAGENTA(BOLD(str(usage.prompt_tokens)))} "
f"({MAGENTA(BOLD(f'{reduction_pct:.0f}% reduction'))}), "
f"completion={usage.completion_tokens}")
else:
print(f" Tokens: prompt={usage.prompt_tokens}, "
f"completion={usage.completion_tokens}, total={usage.total_tokens}")
print(f" Latency: {elapsed:.2f}s ({DIM(latency_extra)})")
print(f" Response: {DIM(text)}{DIM('...') if len(text) >= 120 else ''}")
# Highlight the rate-limit remaining — that's the headline for section 4.
for k in sorted(h.keys()):
if "ai-ratelimit" in k.lower():
value = h[k]
if "remaining" in k.lower():
print(f" {k}: {BLUE(BOLD(value))}")
else:
print(f" {k}: {value}")
return elapsed
def count_tokens(text: str) -> int | None:
if _ENC is None:
return None
return len(_ENC.encode(text))
def section(title: str) -> None:
bar = "=" * 65
print(f"\n{bar}\n{BOLD(title)}\n{bar}")
def main() -> None:
section("1. SEMANTIC ROUTING. Cheap vs Expensive Model Selection")
chat(standard_client, "What is the capital of France?", "SIMPLE")
chat(
standard_client,
"Design a Python FastAPI application with OAuth2 JWT authentication, "
"PostgreSQL integration, WebSocket support, and comprehensive error "
"handling. Include the service architecture and key implementation.",
"COMPLEX",
)
section("2. SEMANTIC CACHING. Cache Hits for Similar Questions")
t_miss = chat(standard_client, "What is machine learning?", "MISS")
time.sleep(1)
t_hit = chat(standard_client, "Explain machine learning to me", "HIT")
if t_hit > 0:
print(f"\n Cache speedup: {GREEN(BOLD(f'{t_miss / t_hit:.1f}x faster'))}")
section("3. PROMPT COMPRESSION. Reduced Token Usage on Long Prompts")
verbose_prompt = (
"I would really like you to provide me with a very detailed and "
"comprehensive explanation of the process of photosynthesis in plants. "
"Please include information about the light-dependent reactions that "
"occur in the thylakoid membranes of the chloroplasts, as well as the "
"light-independent reactions, also known as the Calvin cycle, that take "
"place in the stroma. Additionally, please describe the role of "
"chlorophyll and other photosynthetic pigments in capturing light energy, "
"and explain how water molecules are split during photolysis to release "
"oxygen as a byproduct. I would also appreciate it if you could discuss "
"the importance of photosynthesis for life on Earth and its relationship "
"to the carbon cycle and atmospheric oxygen levels."
)
original = count_tokens(verbose_prompt)
if original is None:
print(" (Install `tiktoken` to see the original-vs-billed token comparison.)")
chat(standard_client, verbose_prompt, "COMPRESSED", original_tokens=original)
print(DIM(" (LLMLingua compressed the prompt server-side before reaching the LLM."))
print(DIM(" 'billed' is the post-compression token count the provider charged for.)"))
section("4. COST-BASED RATE LIMITING. Tiered Budget Caps")
print(" Each consumer sends a unique prompt to bypass the cache and trigger a")
print(" real upstream call so the per-tier budget visibly debits.")
print(f"\n {BOLD('Standard user')} ($1/hour budget):")
chat(standard_client, "Say hello in one sentence.", "STANDARD")
print(f"\n {BOLD('Premium user')} ($5/hour budget):")
chat(premium_client, "Tell me an interesting fact about octopuses in one sentence.", "PREMIUM")
section("5. AUTH BOUNDARY. Invalid API key rejected before upstream call")
bad_key = "not-a-real-key"
print(f" Sending request with apikey='{RED(bad_key)}' (not registered with any Consumer)...")
bad_client = make_client(bad_key)
chat(bad_client, "Hello", "BLOCKED")
print(f" {DIM('Kong rejected the request before any upstream call (no provider quota consumed).')}")
section("DONE. Four cost optimization layers active simultaneously:")
print(f" {GREEN('Semantic routing')}: cheap model for simple, expensive for complex")
print(f" {GREEN('Semantic caching')}: instant $0 responses for similar questions")
print(f" {GREEN('Prompt compression')}: fewer tokens sent to the LLM")
print(f" {GREEN('Cost rate limiting')}: per-consumer dollar-based budget caps")
print("=" * 65)
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
sys.exit(130)
EOF
{:.collapsible}
실행해 보세요:
python demo.py
예시 출력(OpenAI 탭의 모델 환경 변수 사용):
=================================================================
1. SEMANTIC ROUTING. Cheap vs Expensive Model Selection
=================================================================
[SIMPLE] 'What is the capital of France?'
Model: openai/gpt-4o-mini
Cache: Miss
Tokens: prompt=14, completion=7, total=21
Latency: 1.48s (upstream: 589ms)
Response: The capital of France is Paris.
x-ai-ratelimit-limit-hour-openai: 1
x-ai-ratelimit-remaining-hour-openai: 1
[COMPLEX] 'Design a Python FastAPI application with OAuth2 JWT authentication, ...'
Model: openai/gpt-4o
Cache: Miss
Tokens: prompt=40, completion=250, total=290
Latency: 3.40s (upstream: 2870ms)
Response: Designing a Python FastAPI application with OAuth2 JWT authentication, PostgreSQL integration...
x-ai-ratelimit-limit-hour-openai: 1
x-ai-ratelimit-remaining-hour-openai: 0.9999937
=================================================================
2. SEMANTIC CACHING. Cache Hits for Similar Questions
=================================================================
[MISS] 'What is machine learning?'
Model: openai/gpt-4o-mini
Cache: Miss
Tokens: prompt=12, completion=250, total=262
Latency: 3.20s (upstream: 2810ms)
Response: Machine learning is a subset of artificial intelligence (AI) that focuses on the development...
[HIT] 'Explain machine learning to me'
Model: (served from cache)
Cache: Hit
Tokens: prompt=12, completion=250, total=262
Latency: 0.45s (cache hit, no upstream call)
Response: Machine learning is a subset of artificial intelligence (AI) that focuses on the development...
Cache speedup: 7.1x faster
=================================================================
3. PROMPT COMPRESSION. Reduced Token Usage on Long Prompts
=================================================================
[COMPRESSED] 'I would really like you to provide me with a very detailed and comprehen...'
Model: openai/gpt-4o-mini
Cache: Miss
Tokens: pre-compression~138 -> billed=87 (37% reduction), completion=250
Latency: 4.10s (upstream: 3580ms)
Response: Photosynthesis is a vital biochemical process that occurs in green plants, algae, and some...
(LLMLingua compressed the prompt server-side before reaching the LLM.
'billed' is the post-compression token count the provider charged for.)
=================================================================
4. COST-BASED RATE LIMITING. Tiered Budget Caps
=================================================================
Each consumer sends a unique prompt to bypass the cache and trigger a
real upstream call so the per-tier budget visibly debits.
Standard user ($1/hour budget):
[STANDARD] 'Say hello in one sentence.'
Model: openai/gpt-4o-mini
Cache: Miss
Tokens: prompt=13, completion=9, total=22
Latency: 0.96s (upstream: 438ms)
Response: Hello! How can I assist you today?
x-ai-ratelimit-limit-hour-openai: 1
x-ai-ratelimit-remaining-hour-openai: 0.9858
Premium user ($5/hour budget):
[PREMIUM] 'Tell me an interesting fact about octopuses in one sentence.'
Model: openai/gpt-4o-mini
Cache: Miss
Tokens: prompt=15, completion=27, total=42
Latency: 1.08s (upstream: 612ms)
Response: Octopuses have three hearts and blue blood, with two hearts pumping blood to the gills...
x-ai-ratelimit-limit-hour-openai: 5
x-ai-ratelimit-remaining-hour-openai: 4.9999858
=================================================================
5. AUTH BOUNDARY. Invalid API key rejected before upstream call
=================================================================
Sending request with apikey='not-a-real-key' (not registered with any Consumer)...
[BLOCKED] 401 Error code: 401 - {'message': 'Unauthorized'} (0.01s)
Kong rejected the request before any upstream call (no provider quota consumed).
=================================================================
DONE. Four cost optimization layers active simultaneously:
Semantic routing: cheap model for simple, expensive for complex
Semantic caching: instant $0 responses for similar questions
Prompt compression: fewer tokens sent to the LLM
Cost rate limiting: per-consumer dollar-based budget caps
=================================================================
{: .no-copy-code .collapsible }
어떤 일이 일어났나요
-
시맨틱 라우팅은 간단한 사실 확인 질문에는
openai/gpt-4o-mini를, 복잡한 아키텍처 설계 프롬프트에는openai/gpt-4o를 선택했어요.X-Kong-LLM-Model헤더가 각 요청을 처리한 모델을 확인해 줘요. 간단한 쿼리는 1센트의 일부 수준의 비용만 들었고, 복잡한 쿼리는 더 많은 비용이 들었지만 그걸 감당할 수 있는 모델로 라우팅됐어요. -
시맨틱 캐싱은
"Explain machine learning to me"가"What is machine learning?"과 시맨틱적으로 가까웠기 때문에 캐시된 응답을 반환했어요.X-Cache-Status: Hit헤더와X-Kong-Upstream-Latency가 없다는 점이 LLM 호출이 이루어지지 않았음을 확인해 줘요. 응답 시간이 ~6.1초에서 ~0.9초로 줄었어요.Model:이 특정 모델 대신(served from cache)로 표시된다는 점에 유의하세요. AI Semantic Cache Plugin은 AI Proxy Advanced Plugin보다 먼저 실행되기 때문에, 캐시 히트 시에는 라우팅 결정이 완전히 건너뛰어져요. 캐시된 응답은, 원래 그 응답을 만들어낸 모델이 아닌 다른 모델로 라우팅됐을 프롬프트에도 제공될 수 있어요(크로스 모델 캐시에 대한 자세한 내용은 "How it works"를 참고하세요). -
프롬프트 압축은 원래 ~138토큰이던 광합성 프롬프트를 LLM에 도달하기 전에 청구 기준 87토큰으로 줄였어요(
value: 0.6에서 37% 절감). 스크립트가tiktoken으로 원래 토큰 수를 로컬에서 계산하기 때문에 그 차이를 출력에서 확인할 수 있고, LLM에는 압축된 토큰 수만큼만 청구됐어요. -
비용 기반 레이트 리미팅은 티어별로 서로 다른 예산 헤더를 보여줬어요: standard는
x-ai-ratelimit-limit-hour-openai: 1($/시간), premium은5였죠. 각 티어의remaining값은 해당 Consumer 요청에 대해 계산된 비용만큼 차감됐고, 원시 토큰 수가 아닌 실제 달러 지출을 추적했어요. 레시피는 이 값들을 의도적으로 낮게 설정했어요(프로덕션 배포에서는 보통[10]/[100]을 사용해요). 데모를 한 번 실행하는 동안 두 티어 모두에서 차감이 보이도록 하기 위해서예요. 프로덕션용으로 레시피를 조정할 때는 이 값을 올리세요. -
인증 경계는 잘못된 API 키를 약 10ms 만에 거부했는데, 이는 정상적인 업스트림 지연 시간보다 훨씬 짧은 시간이에요. 스크립트는 전송 전에 문제가 된
apikey='not-a-real-key'값을 출력해서 테스트 조건이 보이도록 했어요. 프로바이더는 전혀 호출되지 않았고, 프로바이더 쿼터도 소비되지 않았으며, 클라이언트에게는 깔끔한401로 실패가 전달됐어요.
Konnect에서 살펴보기
Konnect를 열고 API Gateway → Gateways → llm-cost-optimization-recipe로 이동하세요. 레시피가 이 Control Plane에 다음 리소스들을 만들었어요:
- Gateway services → llm-cost-optimization: 레시피가 등록한 Service예요. 상세 페이지에는 Configuration, Routes, Plugins, Analytics 탭이 있어요.
- Routes 탭: 적용할 때 사용한
llm-cost-optimization-recipeselect_tags로 스코프가 지정된/llm-cost-optimizationRoute예요. - Plugins 탭: Route에 있는 네 개의 Plugin 인스턴스가 우선순위 순서대로 있어요:
llm-cost-optimization-auth(key-auth),llm-cost-optimization-cache(ai-semantic-cache),llm-cost-optimization-compressor(ai-prompt-compressor),llm-cost-optimization-proxy(ai-proxy-advanced). AI Proxy Advanced Plugin을 열어 두 개의 타겟과 그description필드를 확인하세요.
- Routes 탭: 적용할 때 사용한
- Consumers → standard-user와 premium-user: API 키로 식별되는 두 개의 Consumer예요.
- Consumer Groups → standard-tier와 premium-tier: 각각 티어별 달러 예산이 담긴 자체
ai-rate-limiting-advancedPlugin 인스턴스를 가지고 있어요.
Gateway service의 Analytics 탭에는 요청 수, 에러율, 평균 지연 시간, 시간별 요청 차트 등 이 레시피와 관련된 분석 데이터가 표시돼요. 이런 분석 데이터를 더 깊이 살펴보고, Consumer별 비용 귀속과 모든 Control Plane에 걸친 플랫폼 전체 분석까지 확인하려면 Konnect의 Observability L1 메뉴로 이동하세요.
변형과 다음 단계
코드 변경 없이 모델 전환하기. DECK_CHAT_MODEL_1, DECK_CHAT_MODEL_2와 그에 대응하는 DECK_INPUT_COST_*, DECK_OUTPUT_COST_* 환경 변수를 업데이트한 다음 다시 적용하세요. 나머지는 Kong이 알아서 처리해 줘요. 현재 토큰당 비용은 프로바이더의 가격 페이지에서 확인하세요. 예를 들어 비싼 타겟을 gpt-4o에서 o3로 바꾸면 기능 프로필과 비용 구조가 모두 달라져요.
워크로드에 맞게 시맨틱 라우팅 설명 조정하기. 타겟의 description 필드가 어떤 쿼리가 비싼 모델로 라우팅되는지 결정해요. 일반적인 "complex analysis" 설명을 여러분의 사용 사례에 맞는 설명으로 바꾸세요. 예를 들어 "Code generation, debugging, and refactoring tasks"나 "Legal document analysis requiring precise citation" 같은 식이에요. 더 구체적인 설명일수록 라우팅 정확도가 향상돼요. 더 세밀한 라우팅을 위해 서로 다른 가격대의 타겟을 추가로 만들 수 있고, 동일한 설명을 가진 여러 타겟에는 라운드 로빈 방식으로 요청이 분배돼요.
서로 다른 예산을 가진 Consumer 티어 더 추가하기. 레시피는 두 개의 티어를 정의하지만, 추가 Consumer Group을 만들 수도 있어요. 예를 들어 시간당 $1인 free 티어, 시간당 $50인 team 티어처럼 각각 자체 ai-rate-limiting-advanced 인스턴스를 두는 거죠. 티어마다 여러 레이트 리밋 윈도우를 추가하면(예: window_size: [60, 3600]과 함께 limit: [5, 50]) 버스트 지출과 지속적인 지출 모두를 제한할 수 있어요.
프로덕션 아이덴티티를 위해 key-auth를 OpenID Connect로 교체하기. 이 레시피는 단순함을 위해 정적 API 키를 사용하지만, 프로덕션 배포에서는 openid-connect Plugin을 사용해 여러분의 아이덴티티 프로바이더와 통합해야 해요. JWT 클레임을 사용하면 역할이나 팀 소속을 기준으로 사용자를 Consumer Group에 자동으로 매핑할 수 있어요. 자체 완결형 JWT 패턴은 basic-llm-routing 레시피를, Okta를 사용한 엔드투엔드 예제는 claude-code-sso 레시피를 참고하세요.
Azure OpenAI에 맞게 조정하기. Azure는 배포별 엔드포인트를 사용하기 때문에 모델 타겟마다 서로 다른 azure_deployment_id가 필요해요. 이 레시피를 Azure에서 사용하려면 deck 설정을 직접 수정해서 각 타겟의 options 블록에 azure_deployment_id, azure_api_version, azure_instance를 설정하세요. 레시피의 나머지 부분(시맨틱 라우팅, 캐싱, 압축, 레이트 리미팅)은 동일하게 동작해요.
정리
레시피는 모든 리소스를 select_tags와 kongctl namespace로 스코프했기 때문에, 이 정리 작업은 이 레시피의 설정만 제거해요. 로컬 Data Plane을 정리하고 Konnect에서 Control Plane을 삭제하세요:
export KONNECT_CONTROL_PLANE_NAME='llm-cost-optimization-recipe' && curl -Ls https://get.konghq.com/quickstart | bash -s -- -d -k $KONNECT_TOKEN
Redis와 LLMLingua 컨테이너를 로컬에서 시작했다면 중지하고 제거하세요:
docker rm -f redis-stack llmlingua-compressor 2>/dev/null
더 알아보기 (Learn more)
- API 키로 Consumer를 식별하는 인증 플러그인이에요 — key-auth
- 시맨틱 라우팅으로 요청을 알맞은 모델과 프로바이더에 보내는 플러그인이에요 — ai-proxy-advanced
- 임베딩 기반으로 응답을 캐싱해 중복 LLM 호출을 없애는 플러그인이에요 — ai-semantic-cache
- LLMLingua로 프롬프트 토큰 수를 줄여주는 플러그인이에요 — ai-prompt-compressor
- Consumer Group별 달러 기반 예산 한도를 설정하는 플러그인이에요 — ai-rate-limiting-advanced
- 시맨틱 라우팅의 기본이 되는 LLM 라우팅 레시피예요 — basic-llm-routing recipe