커스텀 LLM 라우팅
커스텀 LLM 라우팅 (Custom LLM Routing)
이 레시피는 게이트웨이에서 실행되는 커스텀 규칙에 따라 각 채팅 요청을 소형 또는 대형 OpenAI 모델로 라우팅하는 방법을 다뤄요. 공개 Model에 적용한 datakit AI Policy가 입력 크기를 추정하고, 그 결과에 따라 내부의 소형 또는 대형 AI Model을 호출해 응답을 돌려줘요. 모델 디스패치는 Policy가 실행되기 전에 확정되기 때문에 pre-function으로는 Model 별칭 사이를 조율할 수 없다는 점도 짚고 넘어가요. 튜토리얼을 마치면 클라이언트가 모델을 직접 고르지 않아도 Kong이 대신 선택해 주는 단일 엔드포인트를 갖게 돼요
출처: 문서
본문
개요
프록시 전에 게이트웨이에서 실행되는 커스텀 규칙에 따라 각 채팅 요청을 small 또는 large OpenAI 모델로 라우팅해요. 이 레시피는 공개 Model에 datakit AI Policy를 사용해 입력 크기를 추정하고, 내부의 small 또는 large AI Model을 호출한 뒤 그 응답을 반환해요. Model 디스패치는 Policy가 실행되기 전에 최종 확정되기 때문에, pre-function으로는 Model 별칭 사이를 전환할 수 없어요. 이 가이드를 마치면 클라이언트가 모델을 선택하지 않는 단일 엔드포인트를 갖게 돼요. 대신 Kong이 선택해요.
사전 준비
Kong Konnect
이 튜토리얼은 Kong Konnect를 사용해요. 퀵스타트 스크립트를 통해 레시피 전용 AI Gateway와 로컬 Data Plane을 프로비저닝하게 돼요.
-
Konnect PAT 페이지를 열고 Generate Token을 선택해서 새 개인 액세스 토큰을 만들어요.
-
토큰을 내보내요. 이 토큰은 나중에 kongctl 명령에서 다시 사용돼요:
export KONNECT_TOKEN='YOUR_KONNECT_PAT' -
레시피 전용 AI Gateway 이름을 설정하고 퀵스타트 스크립트를 실행해요:
export KONNECT_CONTROL_PLANE_NAME='custom-llm-routing-recipe' curl -Ls https://get.konghq.com/ai | bash -s -- -k $KONNECT_TOKEN이 스크립트는
custom-llm-routing-recipe라는 이름의 AI Gateway와 여기에 연결된 로컬 Data Plane을 프로비저닝하고,AI_GATEWAY_ID를 포함한 나머지 세션 변수들의export라인을 출력해요. 안내가 뜨면 그 내용을 셸에 붙여 넣으세요.
kongctl
이 튜토리얼은 AI Gateway 설정을 관리할 때 kongctl을 사용해요.
-
developer.konghq.com/kongctl에서 kongctl을 설치해요.
-
제대로 설치됐는지 확인해요:
kongctl version
OpenAI
이 튜토리얼은 OpenAI를 사용해요:
-
API 키를 환경 변수로 내보내요:
export DECK_OPENAI_TOKEN='Bearer sk-YOUR-KEY'
Python 3.11+
데모 스크립트에는 Python 3.11 이상이 필요해요. 격리된 환경을 준비해요:
python3 -m venv .venv
source .venv/bin/activate
pip install 'openai>=1.0.0'
문제 상황
플랫폼 팀은 요청 자체에 대한 규칙으로 게이트웨이가 모델 티어를 선택하고, 모든 클라이언트에게 하나의 OpenAI 형식 엔드포인트를 유지해 주길 원하는 경우가 많아요. 빌트인 AI Gateway 라우팅은 이미 이런 판단 중 상당 부분을 커버해요:
- 클라이언트가 선택한 별칭. 앱이
model: fast나model: smart를 보내면 게이트웨이가 그 별칭을 업스트림 모델로 매핑해요. 기본 LLM 라우팅을 참고하세요. - 의미 기반 라우팅. 시맨틱 밸런서와 분류기 LLM이 프롬프트 의도(예: 인사 vs 다단계 추론)를 보고 티어를 골라요. 모델 기반 라우팅을 참고하세요.
- 사용량 기반 로드 밸런싱.
tokens_count_strategy: prompt-tokens와 함께 사용하는lowest-usage같은 알고리즘이 측정된 사용량을 기준으로 트래픽을 여러 타깃에 분산해요. 로드 밸런싱을 참고하세요.
빌트인 옵션만으로도 많은 경우를 커버할 수 있어요. 하지만 정책이 입력 길이나 키워드처럼 이 요청 본문에 대한 규칙일 때는 작은 커스텀 단계를 추가하면서도 모델 별칭을 그대로 쓸 수 있어요. 예를 들어 예상 입력 길이(짧은 프롬프트는 small 모델로, 긴 컨텍스트는 large 모델로)나 프롬프트 안의 특정 단어나 구(제품 코드, 로캘 마커, 워크플로 키워드)를 기준으로 라우팅이 필요할 때가 그래요. 이런 규칙에는 현재 요청 본문에 대한 결정론적 정책이 필요해요. 그런 정책이 필요하다면 게이트웨이가 간단한 커스텀 단계로 티어를 계산하고, 그 결과를 이미 사용 중인 별칭 라우팅으로 넘길 수 있어요.
해결 방법
Kong AI Gateway는 연결된 Policy가 실행되기 전에 어떤 AI Model이 요청을 처리할지 결정해요. 그래서 pre-function에서 model을 재작성해도 별칭을 바꿀 수 없어요. 이 레시피는 공개 /custom-llm-routing Model에 datakit Policy를 올려요. jq가 토큰을 ceil(utf8-bytes / 4)로 추정하고, branch가 내부의 small 또는 large Model을 호출한 뒤, exit이 X-LLM-Tier / X-Prompt-Est-Tokens와 함께 그 응답을 반환해요. 공유하는 AI Model Provider가 OpenAI 자격 증명을 주입해요. 클라이언트는 OpenAI 형식 채팅 요청을 계속 보내면 돼요.
sequenceDiagram
participant C as Client
participant K as Kong AI Gateway
participant O as OpenAI
C->>K: POST /custom-llm-routing (apikey, any model)
activate K
K->>K: key-auth Auth Strategy - validate apikey (else 401)
K->>K: pre-function Policy - estimate tokens, set model small or large
K->>K: AI Model - match route.model.values alias, select target
K->>K: AI Model Provider - inject OpenAI auth
K->>O: chat completions
activate O
O-->>K: completion
deactivate O
K-->>C: OpenAI response + X-LLM-Tier + X-Prompt-Est-Tokens + X-Kong-LLM-Model
deactivate K
클라이언트 애플리케이션
역할: apikey 헤더와 함께 OpenAI 형식 채팅 요청을 보내요. model 필드는 재작성 후에는 무시돼요.
key-auth Auth Strategy
역할: API 키를 검증하고 Consumer를 연결해요.
pre-function Policy
역할: 입력 토큰을 추정하고, model을 small 또는 large로 재작성한 뒤, X-LLM-Tier와 X-Prompt-Est-Tokens를 설정해요.
AI Models (small / large)
역할: /custom-llm-routing을 공유해요. 각각 config.route.model.values로 하나의 별칭을 매칭하고 자신의 타깃을 선택해요.
AI Model Provider
역할: OpenAI 자격 증명을 보관하고 업스트림에 주입해요.
OpenAI
역할: 선택된 모델의 completion을 제공해요.
동작 방식
Kong을 통과하는 요청은 인증, 커스텀 규칙, 별칭 라우팅의 세 단계를 거치며 처리돼요.
- 클라이언트가
apikey헤더와 함께/custom-llm-routing으로 채팅 completion 요청을 보내요. 본문의model값은 이 레시피에서 중요하지 않아요. - key-auth AI Auth Strategy가 키를 검증해요. 키가 없거나 알 수 없는 키는 LLM 호출 전에
401을 반환해요. - pre-function AI Policy가
access페이즈에서 실행돼요.messages[].content의 UTF-8 바이트 길이를 모두 더해 토큰을ceil(bytes / 4)로 추정하고, 그 값을80임계값과 비교한 뒤model을small또는large로 설정해요. - 매칭된 AI Model이 해당 별칭의 타깃을 선택하고, AI Model Provider가 OpenAI 자격 증명을 주입해 요청을 전달해요.
- Kong이
X-LLM-Tier,X-Prompt-Est-Tokens,X-Kong-LLM-Model과 함께 OpenAI 형식 응답을 반환해요.
Key Auth: API 키 인증과 Consumer 매핑
Kong AI Gateway 2.0에서는 인증이 Policy가 아니라 AI Auth Strategy로 수행돼요. 이 레시피는 데모 API 키를 가진 Consumer를 하나 등록해요. 매칭에 성공하면 분석과 토큰 레이트 리밋 같은 이후 정책에서 사용할 수 있도록 그 Consumer가 연결돼요.
설정 세부 사항
ai_gateway_auth_strategies:
- type: key-auth
config:
key_names:
- apikey
hide_credentials: true
{:.no-copy-code}
key_names: [apikey]. Consumer API 키를 담는 헤더예요. OpenAI SDK의 api_key 필드는 Authorization: Bearer ...가 되는데, Key Auth는 이걸 API 키 매칭으로 취급하지 않아요. 그래서 데모는 default_headers를 통해 apikey를 보내요.
hide_credentials: true. 업스트림 호출 전에 Consumer 키를 제거해서 OpenAI가 키를 받지 않게 해요.
Pre-function: 커스텀 라우팅 규칙
pre-function AI Policy는 access 페이즈에서 샌드박스 Lua를 실행해요. 두 AI Model 모두 이 Policy를 붙여서 본문 재작성이 별칭 매칭 전에 일어나요. 이 레시피의 규칙은 추정 입력 크기예요. 같은 패턴은 헤더 값, JSON 필드, 경로 캡처 같은 다른 요청 파생 규칙에도 적용돼요.
여기서는 Policy가 인증보다 먼저 오는 순서가 필요하지 않아요. Key Auth를 위해
Authorization을apikey로 재작성하는 레시피와 달리, 이 Policy는 인증 이후에 JSONmodel필드만 재작성해요. Lua를 확장해 인증 헤더를 다루게 된다면kongctl explain으로 Policy 부착 순서를 확인하세요.
설정 세부 사항
ai_gateway_policies:
- type: pre-function
config:
access:
- |
local cjson = require("cjson.safe")
local data = cjson.decode(kong.request.get_raw_body() or "{}") or {}
local chars = 0
local function add(s)
if type(s) == "string" then
chars = chars + #s
elseif type(s) == "table" then
for _, v in ipairs(s) do
add(type(v) == "table" and (v.text or v) or v)
end
end
end
for _, msg in ipairs(data.messages or {}) do
add(msg.content)
end
local tokens = math.max(1, math.ceil(chars / 4))
local threshold = 80
local tier = tokens >= threshold and "large" or "small"
data.model = tier
kong.service.request.set_raw_body(cjson.encode(data))
kong.response.set_header("X-Prompt-Est-Tokens", tostring(tokens))
kong.response.set_header("X-LLM-Tier", tier)
{:.no-copy-code}
ceil(bytes / 4). 데모와 정책 임계값에 쓸 수 있는 간단한 입력 토큰 추정치예요. 프로바이더 토크나이저는 아니에요. 정확한 개수가 필요하다면 프로덕션에서는 이 추정을 토크나이저 호출로 교체하세요.
threshold = 80. 추정 토큰 기준의 컷오프 값이에요. 이 값 이상인 프롬프트는 large를 사용해요. 튜닝하려면 Pre-function 본문에서 숫자를 바꾸고 다시 적용하세요. 데모의 DECK_TOKEN_THRESHOLD export도 이 값과 맞춰 두어야 검증이 정확하게 유지돼요.
응답 헤더. X-Prompt-Est-Tokens와 X-LLM-Tier 덕분에 Gateway 내부를 조회하지 않고도 판단 결과를 확인할 수 있어요.
대안 규칙. 크기 휴리스틱은 data.model을 별칭 문자열로 설정하는 어떤 샌드박스 로직으로도 바꿀 수 있어요. VIP Consumer를 large로 라우팅하거나, X-Model-Tier 헤더를 존중하거나, metadata.priority 같은 JSON 필드로 분기할 수 있어요.
AI Models: 별칭 라우팅
두 개의 AI Model이 /custom-llm-routing 경로를 공유해요. pre-function이 본문을 재작성한 뒤, Kong이 model을 각 Model의 config.route.model.values(small 또는 large)와 매칭하고 설정된 OpenAI 타깃으로 요청을 보내요. 클라이언트는 자리표시용 model 값을 계속 보내도 돼요. Kong이 덮어써요.
설정 세부 사항
ai_gateway_models:
- name: custom-llm-routing-small
config:
route:
paths:
- /custom-llm-routing
model:
body_param: model
values:
- small
targets:
- name: ${DECK_CHAT_MODEL_1}
provider: custom-llm-routing-provider
- name: custom-llm-routing-large
config:
route:
paths:
- /custom-llm-routing
model:
body_param: model
values:
- large
targets:
- name: ${DECK_CHAT_MODEL_2}
provider: custom-llm-routing-provider
{:.no-copy-code}
config.route.model.values. Model의 클라이언트용(또는 Pre-function이 기록한) 별칭이에요.
공유 경로. 두 Model 모두 /custom-llm-routing에서 리슨해요. 별칭 매칭이 어떤 Model이 요청을 처리할지 선택해요.
프로바이더 자격 증명. Kong은 OpenAI 자격 증명을 AI Model Provider에 보관하고 업스트림에 주입해요. 클라이언트는 Consumer API 키만 갖고 있으면 돼요.
프로덕션에서는 환경 변수 대신
{vault://backend/key}참조를 사용해 자격 증명을 Kong Vaults에 저장하세요. Kong은 HashiCorp Vault, AWS Secrets Manager, GCP Secret Manager, Konnect Config Store를 지원해요.
Kong 구성 적용하기
다음 구성은 OpenAI 자격 증명을 담고 있는 AI Model Provider, 데모 API 키를 가진 key-auth AI Auth Strategy와 Consumer, 토큰 크기 라우팅을 위한 pre-function Policy, 그리고 /custom-llm-routing을 공유하는 두 개의 AI Model(small과 large)을 생성해요. 모든 리소스는 kongctl 네임스페이스로 스코프가 지정되기 때문에, 같은 AI Gateway에 있는 다른 구성에 영향을 주지 않고 깔끔하게 정리할 수 있어요. 연합(federated) 구성 관리에 대해 더 자세히 알아보려면 kongctl 문서를 참고하세요.
먼저 퀵스타트 AI Gateway를 kongctl 네임스페이스에 adopt하세요. 그래야 다음 apply 명령이 이를 관리할 수 있어요.
kongctl adopt ai-gateway "${KONNECT_CONTROL_PLANE_NAME}" \
--namespace "${KONNECT_CONTROL_PLANE_NAME}" \
--pat "${KONNECT_TOKEN}"
Adopt하면 AI Gateway에 KONGCTL-namespace 라벨이 찍혀요.
데모 Consumer의 API 키를 내보내세요. Consumer 자격 증명의 api_key 필드는 write-only라서, 이 고정된 데모 값인 경우에도 반드시 환경 변수로 제공해야 해요:
export DECK_CONSUMER_API_KEY='demo-api-key'
모델 환경 변수를 내보내세요. DECK_CHAT_MODEL_1은 small 티어예요. DECK_CHAT_MODEL_2는 large 티어예요. DECK_TOKEN_THRESHOLD는 Pre-function 임계값(80)에 맞추세요:
export DECK_CHAT_MODEL_1='gpt-4o-mini' # small alias
export DECK_CHAT_MODEL_2='gpt-4o' # large alias
export DECK_TOKEN_THRESHOLD='80'
Kong 구성을 적용하세요:
cat <<'EOF' > kong-recipe.yaml
_defaults:
kongctl:
namespace: custom-llm-routing-recipe
ai_gateway_model_providers:
- ref: custom-llm-routing-provider
ai_gateway: !lookup {id: !env 'AI_GATEWAY_ID'}
name: custom-llm-routing-provider
display_name: custom-llm-routing
type: openai
config:
auth:
type: basic
headers:
- name: Authorization
value: !secret {source: !env 'DECK_OPENAI_TOKEN'}
ai_gateway_auth_strategies:
- ref: custom-llm-routing-auth
ai_gateway: !lookup {id: !env 'AI_GATEWAY_ID'}
name: custom-llm-routing-auth
display_name: custom-llm-routing key auth
type: key-auth
config:
key_names:
- apikey
hide_credentials: true
ai_gateway_consumers:
- ref: custom-llm-routing-consumer
ai_gateway: !lookup {id: !env 'AI_GATEWAY_ID'}
name: custom-llm-routing-consumer
display_name: custom-llm-routing demo consumer
type: api-key
credentials:
- ref: custom-llm-routing-credential
name: custom-llm-routing-credential
display_name: custom-llm-routing demo API key
type: api-key
api_key: !secret {source: !env 'DECK_CONSUMER_API_KEY'}
ai_gateway_policies:
- ref: custom-llm-routing-orchestrator
ai_gateway: !lookup {id: !env 'AI_GATEWAY_ID'}
name: custom-llm-routing-orchestrator
display_name: custom-llm-routing token size orchestrator
type: datakit
config:
nodes:
- name: EXTRACT_PROMPT
type: jq
input: request.body
jq: '{messages: .messages}'
- name: EXTRACT_AUTH
type: jq
input: request.headers
jq: '{apikey: (.apikey // .Apikey // .APIKEY)}'
- name: ESTIMATE_TIER
type: jq
input: request.body
jq: "(
[ (.messages // [])[]
| .content
| if type == \"string\"\
\ then length
elif type == \"array\" then
([.[] | if type\
\ == \"object\" then ((.text // \"\") | length) elif type == \"string\" then\
\ length else 0 end] | add // 0)
else 0 end
] | add // 0
) as $chars
\
| ([ ($chars / 4 | ceil), 1 ] | max) as $tokens
| {
tokens: $tokens,
\
\ tier: (if $tokens >= 80 then \"large\" else \"small\" end)
}
"
- name: BUILD_DIAG_HEADERS
type: jq
input: ESTIMATE_TIER
jq: "{
\"X-LLM-Tier\": .tier,
\"X-Prompt-Est-Tokens\": (.tokens | tostring)
\
}
"
- name: IS_LARGE
type: jq
input: ESTIMATE_TIER
jq: .tier == "large"
- name: ROUTE_DECISION
type: branch
input: IS_LARGE
then:
- CALL_LARGE
- RESPOND_LARGE
else:
- CALL_SMALL
- RESPOND_SMALL
- name: CALL_SMALL
type: call
url: http://localhost:8000/custom-llm-routing-small
method: POST
inputs:
body: EXTRACT_PROMPT
headers: EXTRACT_AUTH
- name: CALL_LARGE
type: call
url: http://localhost:8000/custom-llm-routing-large
method: POST
inputs:
body: EXTRACT_PROMPT
headers: EXTRACT_AUTH
- name: RESPOND_SMALL
type: exit
inputs:
body: CALL_SMALL.body
headers: BUILD_DIAG_HEADERS
- name: RESPOND_LARGE
type: exit
inputs:
body: CALL_LARGE.body
headers: BUILD_DIAG_HEADERS
ai_gateway_models:
- ref: custom-llm-routing-small
ai_gateway: !lookup {id: !env 'AI_GATEWAY_ID'}
name: custom-llm-routing-small
display_name: custom-llm-routing (small internal)
type: model
formats:
- type: openai
capabilities:
- generate
access:
auth_strategies:
- custom-llm-routing-auth
config:
max_request_body_size: 10485760
response_streaming: deny
logging:
payloads: true
route:
paths:
- /custom-llm-routing-small
protocols:
- http
- https
methods:
- POST
- OPTIONS
strip_path: true
targets:
- name: !env 'DECK_CHAT_MODEL_1'
provider: custom-llm-routing-provider
config:
type: openai
- ref: custom-llm-routing-large
ai_gateway: !lookup {id: !env 'AI_GATEWAY_ID'}
name: custom-llm-routing-large
display_name: custom-llm-routing (large internal)
type: model
formats:
- type: openai
capabilities:
- generate
access:
auth_strategies:
- custom-llm-routing-auth
config:
max_request_body_size: 10485760
response_streaming: deny
logging:
payloads: true
route:
paths:
- /custom-llm-routing-large
protocols:
- http
- https
methods:
- POST
- OPTIONS
strip_path: true
targets:
- name: !env 'DECK_CHAT_MODEL_2'
provider: custom-llm-routing-provider
config:
type: openai
- ref: custom-llm-routing-chat
ai_gateway: !lookup {id: !env 'AI_GATEWAY_ID'}
name: custom-llm-routing-chat
display_name: custom-llm-routing (public)
type: model
formats:
- type: openai
capabilities:
- generate
access:
auth_strategies:
- custom-llm-routing-auth
policies:
- custom-llm-routing-orchestrator
config:
max_request_body_size: 10485760
response_streaming: deny
logging:
payloads: true
route:
paths:
- /custom-llm-routing
protocols:
- http
- https
methods:
- POST
- OPTIONS
strip_path: true
targets:
- name: !env 'DECK_CHAT_MODEL_1'
provider: custom-llm-routing-provider
config:
type: openai
EOF
kongctl apply -f kong-recipe.yaml -o text --auto-approve --pat "${KONNECT_TOKEN}"
rm -f kong-recipe.yaml
{: data-test-step="block" .collapsible }
직접 사용해 보기
데모는 짧은 프롬프트(hi)와 긴 프롬프트(x를 400번 반복한 것)를 보내요. 둘 다 model: ignored-by-router를 사용해요. Kong은 X-LLM-Tier를 small로 설정했다가 large로 설정해야 하고, X-Kong-LLM-Model은 별칭 매핑을 따라야 해요.
데모는 OpenAI SDK가
api_key를Authorization: Bearer헤더용으로 예약해 두기 때문에 API 키를default_headers로 전달해요. 클라이언트가api_key를 통해 키를 직접 전달하게 하려면, Bearer 토큰을 서버 측에서apikey헤더로 복사하는 pre-function Policy를 붙이세요. 패턴은 Key Auth로 OpenAI SDK 클라이언트 인증하기를 참고하세요.
데모 스크립트를 만드세요:
cat <<'EOF' > demo.py
"""Custom LLM routing demo.
Sends a short and a long prompt through Kong. The pre-function Policy estimates
input size, rewrites the request model to small or large, and AI Models route
to the matching OpenAI target. The client model field is ignored.
Expected output:
- Short prompt -> X-LLM-Tier=small and X-Kong-LLM-Model ending in the small model
- Long prompt -> X-LLM-Tier=large and X-Kong-LLM-Model ending in the large model
Run:
export PROXY_URL=http://localhost:8000
python demo.py
"""
from __future__ import annotations
import os
import sys
import time
from openai import APIStatusError, OpenAI
PROXY_URL = os.getenv("PROXY_URL", "http://localhost:8000")
API_KEY = "demo-api-key"
THRESHOLD = int(os.getenv("DECK_TOKEN_THRESHOLD", "80"))
_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
def BOLD(s: str) -> str:
return _c("1", s)
def DIM(s: str) -> str:
return _c("2", s)
def GREEN(s: str) -> str:
return _c("32", s)
def CYAN(s: str) -> str:
return _c("36", s)
def RED(s: str) -> str:
return _c("31", s)
def YELLOW(s: str) -> str:
return _c("33", s)
def make_client() -> OpenAI:
return OpenAI(
base_url=f"{PROXY_URL}/custom-llm-routing",
api_key="unused",
default_headers={"apikey": API_KEY},
)
def est_tokens(content: str) -> int:
# Matches the Pre-function heuristic: ceil(utf8-bytes / 4).
return max(1, (len(content.encode("utf-8")) + 3) // 4)
def call(client: OpenAI, label: str, content: str) -> None:
tokens = est_tokens(content)
expected = "large" if tokens >= THRESHOLD else "small"
print(f"\n{BOLD('[REQUEST]')} {label}")
print(
f" {DIM(f'est_tokens={tokens} threshold={THRESHOLD} expected_tier={expected}')}"
)
print(f" {DIM(f'client model field=ignored-by-router prompt_preview={content[:48]!r}')}")
start_ms = round(time.time() * 1000)
try:
raw = client.chat.completions.with_raw_response.create(
model="ignored-by-router",
messages=[{"role": "user", "content": content}],
)
except APIStatusError as e:
elapsed_ms = round(time.time() * 1000) - start_ms
print(
f"{RED(BOLD('[ERROR]'))} {RED(BOLD(str(e.status_code)))} "
f"{e.message} ({elapsed_ms}ms)"
)
raise SystemExit(1) from e
elapsed_ms = round(time.time() * 1000) - start_ms
completion = raw.parse()
tier = raw.headers.get("x-llm-tier", ".")
est = raw.headers.get("x-prompt-est-tokens", ".")
upstream_model = raw.headers.get("x-kong-llm-model", ".")
answer = (completion.choices[0].message.content or "")[:120]
print(f"[RESPONSE] {DIM(answer)}")
print(
f"{GREEN(BOLD('[ROUTED TO]'))} tier={GREEN(BOLD(tier))} "
f"est_tokens={YELLOW(BOLD(est))} "
f"upstream={CYAN(BOLD(upstream_model))}"
)
print(f"[LATENCY] {DIM(f'total={elapsed_ms}ms')}")
if tier != expected:
print(
f"{RED(BOLD('[MISMATCH]'))} expected tier={expected!r}, got={tier!r}"
)
raise SystemExit(1)
def section(title: str) -> None:
bar = "=" * 70
print(f"\n{bar}\n{BOLD(title)}\n{bar}")
def main() -> None:
section("1. Short prompt routes to small")
client = make_client()
call(client, "short", "hi")
section("2. Long prompt routes to large")
long_prompt = "x" * 400
call(client, "long", long_prompt)
section("Done.")
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
sys.exit(130)
EOF
{:.collapsible}
실행해 보세요:
python demo.py
예시 출력:
======================================================================
1. Short prompt routes to small
======================================================================
[REQUEST] short
est_tokens=1 threshold=80 expected_tier=small
client model field=ignored-by-router prompt_preview='hi'
[RESPONSE] Hello! How can I help you today?
[ROUTED TO] tier=small est_tokens=1 upstream=openai/gpt-4o-mini
[LATENCY] total=812ms
======================================================================
2. Long prompt routes to large
======================================================================
[REQUEST] long
est_tokens=100 threshold=80 expected_tier=large
client model field=ignored-by-router prompt_preview='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
[RESPONSE] It looks like your message is a long string of x characters...
[ROUTED TO] tier=large est_tokens=100 upstream=openai/gpt-4o
[LATENCY] total=1404ms
======================================================================
Done.
======================================================================
{:.no-copy-code}
무슨 일이 일어났나요
- 짧은 프롬프트는 small 별칭을 사용했어요.
hi는 1토큰으로 추정되며, 임계값 80보다 낮아요. Pre-function이model을small로 설정했어요.X-Kong-LLM-Model은openai/gpt-4o-mini를 표시해요. - 긴 프롬프트는 large 별칭을 사용했어요. 400개의
x문자는 100토큰으로 추정돼요. Pre-function이model을large로 설정했어요.X-Kong-LLM-Model은openai/gpt-4o를 표시해요. - 클라이언트의
model필드는 무시됐어요. 두 호출 모두ignored-by-router를 보냈어요. Kong이 AI Model 별칭 매칭 전에 이를 덮어썼어요. - 프로바이더 자격 증명은 Kong에 유지됐어요. SDK는 Consumer API 키만 갖고 있었어요.
DECK_OPENAI_TOKEN은 AI Model Provider가 주입했어요.
Konnect에서 살펴보기
Konnect를 열고 custom-llm-routing-recipe라는 이름의 AI Gateway를 찾아보세요. 이 레시피는 OpenAI 자격 증명을 담고 있는 AI Model Provider, 두 개의 AI Model(custom-llm-routing-small과 custom-llm-routing-large), key-auth AI Auth Strategy, pre-function Policy, 그리고 데모 API 키 자격 증명을 가진 Consumer를 생성했어요. 이 모든 것은 위에서 적용한 kongctl 네임스페이스에 의해 이 레시피로 범위가 한정돼요.
모든 AI Gateway에 걸친 플랫폼 전체 트래픽 분석을 보려면 Konnect의 Observability L1 메뉴로 이동하세요.
변형과 다음 단계
커스텀 규칙 변경하기. pre-function + 별칭 구조는 유지하면서 크기 휴리스틱만 교체하세요. 요청 헤더, JSON 필드, 또는 Consumer 메타데이터를 기준으로 라우팅하세요. model에 small 또는 large를 작성하기만 하면 AI Model 타깃은 그대로 유지돼요.
임계값 다시 조정하기. Pre-function 본문에서 local threshold = 80을 편집하고, 다시 적용한 후, 데모를 실행하기 전에 DECK_TOKEN_THRESHOLD를 같은 값으로 설정하세요.
프로바이더 토크나이저 사용하기. 정확한 청구 정합성이 중요한 경우에는 ceil(bytes / 4)를 프로바이더 토크나이저로 교체하세요. 별칭으로 재작성하는 단계는 유지하세요.
의미 기반 라우팅과 결합하기. 판단 기준이 프롬프트 복잡도라면 Model-Based Routing을 사용하고, 그 위에 컨텍스트 윈도우나 비용 상한을 위한 Pre-function 크기 게이트를 추가하세요.
Consumer별 토큰 예산 추가하기. Key Auth 뒤에 ai-rate-limiting-advanced Policy를 붙여서 각 앱이 자체 토큰 할당량을 갖도록 하세요. 자세한 내용은 LLM Cost Optimization을 확인하세요.
정리
레시피의 kongctl 네임스페이스가 모든 리소스의 범위를 지정했기 때문에, 이 teardown은 이 레시피의 구성만 제거해요. 로컬 Data Plane을 정리하고 Konnect에서 AI Gateway를 삭제하세요:
export KONNECT_CONTROL_PLANE_NAME='custom-llm-routing-recipe' && curl -Ls https://get.konghq.com/ai | bash -s -- -d -k $KONNECT_TOKEN
더 알아보기 (Learn more)
- 이 레시피의 핵심인 datakit 정책으로 요청을 검사하고 커스텀 로직을 실행하는 방법을 설명해요 — datakit
- 라우팅 대상이 되는 AI Model 엔티티의 구성 방법을 다뤄요 — AI Model
- 커스텀 라우팅 규칙을 실행하는 pre-function 정책의 동작 방식을 설명해요 — pre-function
- 클라이언트가 모델 별칭을 선택하는 기본적인 LLM 라우팅 방법을 이 레시피와 비교해 볼 수 있어요 — Basic LLM Routing
- 프롬프트 의미를 기준으로 모델을 고르는 라우팅 방식을 소개해요 — Model-Based Routing
- 모델 선택으로 LLM 비용을 최적화하는 관련 레시피예요 — LLM Cost Optimization