본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

Kong Identity로 AI 모델에 계층별 AI 예산 적용

원문 보기 위키 갱신

Kong Identity로 AI 모델에 계층별 AI 예산 적용 (Enforce tiered AI budgets on AI Models with Kong Identity)

이 가이드에서는 Kong Identity가 발급한 토큰의 클레임을 활용해 AI 모델에 계층별 AI 예산을 적용하는 방법을 알아봐요. AI Auth Strategy가 토큰을 검증해 클레임을 요청 헤더로 전달하고, standard와 premium 두 AI 모델이 서로 다른 AI Consumer Group을 거부하도록 구성해요. 그리고 AI Rate Limiting Advanced Policy로 계층별 지출 상한에 조직 공유 풀과 개인별 한도를 더해, 어떤 모델이 요청을 처리하든 가장 낮은 상한이 먼저 적용되도록 만들어요

출처: 문서

본문

TL;DR

Kong Identity 클레임으로 티어별 AI 예산은 어떻게 강제하나요? Kong Identity 기반의 AI Auth Strategy를 만들고, 이어서 둘 다 이 전략을 통해 인증하면서 서로 다른 AI Consumer Group을 거부하는 표준 AI Model과 프리미엄 AI Model을 만들어요. 티어별 상한에 더해 공유 조직 풀과 개인 한도가 포함된 AI Rate Limiting Advanced Policy를 연결해요. 일치하는 모든 상한이 청구되고, 어떤 모델이 요청을 처리하든 가장 낮은 상한이 적용돼요.

필수 조건

시리즈 필수 조건

이 페이지는 Kong Identity로 티어별 AI 예산 강제하기 시리즈의 일부예요.

이 페이지를 진행하기 전에 이전 페이지인 티어별 AI 예산을 위한 Kong Identity 인증 서버 설정하기를 먼저 완료하세요.

kongctl   v1.20.2+

이 튜토리얼은 kongctl을 사용해 Konnect 리소스를 프로그래밍 방식으로 관리해요. kongctl을 최신 버전(1.20.2)으로 유지하는 것을 권장해요.

  1. developer.konghq.com/kongctl에서 kongctl을 설치하세요.

  2. 설치를 확인하세요:

    kongctl version
    

OpenAI API 키

  1. OpenAI 계정 생성하기.
  2. API 키 발급받기.
  3. API 키를 변수로 내보내세요:
    export OPENAI_API_KEY="<YOUR_OPENAI_API_KEY>"
    export OPENAI_AUTH_HEADER="Bearer $OPENAI_API_KEY"
    

Kong Identity 발급자와 페르소나별 자격 증명

먼저 티어별 AI 예산을 위한 Kong Identity 인증 서버 설정하기를 완료하세요. 해당 가이드의 $ISSUER_URL과 각 페르소나의 클라이언트 ID, 시크릿이 필요해요.

개요

티어별 AI 예산을 위한 Kong Identity 인증 서버 설정하기에서는 다섯 명의 예제 호출자 각각에게 티어, 개인 지출 한도, 공유 조직 풀, 그룹 멤버십을 클레임으로 담은 토큰을 발급했어요. 이 가이드는 그 토큰들을 AI Gateway와 연결해요:

  • AI Auth Strategy가 각 토큰을 검증하고 클레임을 요청 헤더에 매핑해요.
  • 표준 AI Model과 프리미엄 AI Model이 둘 다 그 헤더를 확인하지만 서로 다른 호출자를 거부해요.
  • AI Rate Limiting Advanced Policy가 티어별 지출 상한을 강제하고, 이전 가이드의 공유 조직 풀과 개인 한도도 함께 강제해요.

AI Consumer Group, AI Auth Strategy, AI Model Provider, AI Model 생성하기

다음 항목들을 생성해요:

tokens_count_strategy: cost는 각 요청을 달러 단위로 청구해요. 따라서 요청이 더 저렴한 gpt-4o-mini에 도착하든 더 비싼 gpt-4o에 도착하든 동일한 상한이 적용돼요:

kongctl apply -f - --auto-approve --pat "$KONNECT_TOKEN" << 'EOF'
ai_gateway_consumer_groups:
  - ref: contractors
    ai_gateway: !lookup {id: !env AI_GATEWAY_ID}
    display_name: contractors
    name: contractors
  - ref: suspended
    ai_gateway: !lookup {id: !env AI_GATEWAY_ID}
    display_name: suspended
    name: suspended
ai_gateway_auth_strategies:
  - ref: budget-identity
    ai_gateway: !lookup {id: !env AI_GATEWAY_ID}
    display_name: "Budget identity"
    name: budget-identity
    type: openid-connect
    config:
      issuer: !env ISSUER_URL
      auth_methods: [bearer]
      consumer_optional: true
      consumer_groups_claim: [kong_groups]
      consumer_groups_optional: true
      upstream_headers_claims: [sub, budget_tier, budget_org, budget_cap]
      upstream_headers_names: [x-budget-sub, x-budget-tier, x-budget-org, x-budget-cap]
      cache_tokens_salt: budgets-cache-salt
ai_gateway_model_providers:
  - ref: generic-openai
    ai_gateway: !lookup {id: !env AI_GATEWAY_ID}
    name: generic-openai
    type: openai
    config:
      auth:
        type: basic
        headers:
          - name: Authorization
            value: !secret {source: !env OPENAI_AUTH_HEADER}
ai_gateway_policies:
  - ref: budget-limits
    ai_gateway: !lookup {id: !env AI_GATEWAY_ID}
    name: budget-limits
    display_name: "Budget limits"
    type: ai-rate-limiting-advanced
    enabled: true
    global: false
    config:
      strategy: local
      policies:
        - match:
            - { type: header, key: x-budget-tier, values: [baseline] }
            - { type: header, key: x-budget-sub, partition_by: true }
          window_type: sliding
          limits: [{ limit: 0.05, window_size: 60, tokens_count_strategy: cost }]
        - match:
            - { type: header, key: x-budget-tier, values: ["2x"] }
            - { type: header, key: x-budget-sub, partition_by: true }
          window_type: sliding
          limits: [{ limit: 0.10, window_size: 60, tokens_count_strategy: cost }]
        - match:
            - { type: header, key: x-budget-tier, values: ["4x"] }
            - { type: header, key: x-budget-sub, partition_by: true }
          window_type: sliding
          limits: [{ limit: 0.20, window_size: 60, tokens_count_strategy: cost }]
        - match:
            - { type: header, key: x-budget-sub, partition_by: true }
          window_type: sliding
          limits: [{ limit: 0.20, window_size: 60, tokens_count_strategy: cost }]
        - match:
            - { type: header, key: x-budget-org, values: [live-balance], partition_by: false }
          window_type: sliding
          limits: [{ limit: 0.35, window_size: 60, tokens_count_strategy: cost }]
        - match:
            - { type: header, key: x-budget-cap, values: [strict] }
            - { type: header, key: x-budget-sub, partition_by: true }
          window_type: sliding
          limits: [{ limit: 0.02, window_size: 60, tokens_count_strategy: cost }]
ai_gateway_models:
  - ref: budget-chat
    ai_gateway: !lookup {id: !env AI_GATEWAY_ID}
    display_name: "Budget chat"
    name: budget-chat
    type: model
    enabled: true
    formats: [{ type: openai }]
    capabilities: [generate]
    access:
      auth_strategies:
        - !ref budget-identity#name
      acls:
        deny:
          - suspended
    policies:
      - !ref budget-limits#name
    config:
      route:
        paths: [/v1]
        model:
          body_param: model
          values: [budget-chat]
    targets:
      - name: gpt-4o-mini
        provider: generic-openai
        config:
          type: openai
          input_cost: 0.15
          output_cost: 0.60
  - ref: budget-chat-premium
    ai_gateway: !lookup {id: !env AI_GATEWAY_ID}
    display_name: "Budget chat premium"
    name: budget-chat-premium
    type: model
    enabled: true
    formats: [{ type: openai }]
    capabilities: [generate]
    access:
      auth_strategies:
        - !ref budget-identity#name
      acls:
        deny:
          - contractors
          - suspended
    policies:
      - !ref budget-limits#name
    config:
      route:
        paths: [/v1]
        model:
          body_param: model
          values: [budget-chat-premium]
    targets:
      - name: gpt-4o
        provider: generic-openai
        config:
          type: openai
          input_cost: 2.50
          output_cost: 10.00
EOF

{: data-test-step="block" }

요청은 요청 본문의 model 필드를 통해 모델을 선택해요. budget-limits의 네 번째 정책은 subject 헤더만으로 매칭되기 때문에 항상 적용되고, 일치하는 상한 중 가장 낮은 것이 실제 한도가 돼요.

검증

티어별 AI 예산을 위한 Kong Identity 인증 서버 설정에서 보여준 클라이언트 자격 증명 그랜트를 사용해 각 페르소나의 베어러 토큰을 발급받은 뒤, 어느 쪽 모델로든 요청을 보내세요. 아래 요청들 중 어느 것도 x-budget-* 헤더를 직접 설정하지 않아요. 요청이 budget-limits나 업스트림 모델에 도달하기 전에 budget-identity가 각 토큰의 클레임에서 내부적으로 도출해요.

인증되지 않은 요청은 거부돼요:

curl -X POST "$KONNECT_PROXY_URL/v1/chat/completions" \
     --no-progress-meter --fail-with-body  \
     -H "Content-Type: application/json" \
     --json '{
       "model": "budget-chat",
       "messages": [
         {
           "role": "user",
           "content": "What is DNS?"
         }
       ]
     }'

요청은 401 Unauthorized로 실패해요.

Carol(tier: "4x")은 인증하고 4x 상한 기준으로 청구돼요. 그녀의 클라이언트용 토큰을 생성하고 내보내세요:

CAROL_ACCESS_TOKEN=$(curl -X POST "$ISSUER_URL/oauth/token" \
     --no-progress-meter --fail-with-body  \
     -H "Content-Type: application/x-www-form-urlencoded" \
     -d "grant_type=client_credentials" \
     -d "client_id=$CAROL_CLIENT_ID" \
     -d "client_secret=$CAROL_CLIENT_SECRET" \
     -d "scope=budgets-access"  | jq -r ".access_token"
)

그녀의 토큰으로 요청을 보내세요:

curl -X POST "$KONNECT_PROXY_URL/v1/chat/completions" \
     --no-progress-meter --fail-with-body  \
     -H "Content-Type: application/json"\
     -H "Authorization: Bearer $CAROL_ACCESS_TOKEN" \
     --json '{
       "model": "budget-chat",
       "messages": [
         {
           "role": "user",
           "content": "What is DNS?"
         }
       ]
     }'

Carol은 contractors나 suspended에 속하지 않으므로, 같은 토큰이 프리미엄 모델에도 도달해요:

curl -X POST "$KONNECT_PROXY_URL/v1/chat/completions" \
     --no-progress-meter --fail-with-body  \
     -H "Content-Type: application/json"\
     -H "Authorization: Bearer $CAROL_ACCESS_TOKEN" \
     --json '{
       "model": "budget-chat-premium",
       "messages": [
         {
           "role": "user",
           "content": "What is DNS?"
         }
       ]
     }'

budget-limits는 어느 쪽이든 같은 4x 상한으로 청구해요. 정책은 요청을 처리한 모델이 아니라 헤더를 읽기 때문이에요. 두 모델 간에 달라지는 것은 access.acls뿐인데, 이 가이드의 다섯 페르소나 중 어느 것도 contractors에 속하지 않으므로 이 가이드만으로는 budget-chat-premium에서는 거부되지만 budget-chat에서는 수락되는 요청을 보여줄 수 없어요. 이전 가이드에서 다른 클라이언트들을 만든 것과 같은 방식으로 groups: "contractors" 레이블을 가진 클라이언트를 만들어 보세요. 그러면 budget-chat-premium에서는 거부되면서 여전히 budget-chat에는 도달해요.

Dave(tier: "4x", cap: "strict")도 같은 방식으로 인증하지만, 그의 개인 상한과 티어 상한이 함께 청구되고 더 낮은 쪽이 실제로 적용돼요:

DAVE_ACCESS_TOKEN=$(curl -X POST "$ISSUER_URL/oauth/token" \
     --no-progress-meter --fail-with-body  \
     -H "Content-Type: application/x-www-form-urlencoded" \
     -d "grant_type=client_credentials" \
     -d "client_id=$DAVE_CLIENT_ID" \
     -d "client_secret=$DAVE_CLIENT_SECRET" \
     -d "scope=budgets-access"  | jq -r ".access_token"
)
curl -X POST "$KONNECT_PROXY_URL/v1/chat/completions" \
     --no-progress-meter --fail-with-body  \
     -H "Content-Type: application/json"\
     -H "Authorization: Bearer $DAVE_ACCESS_TOKEN" \
     --json '{
       "model": "budget-chat",
       "messages": [
         {
           "role": "user",
           "content": "What is DNS?"
         }
       ]
     }'

Dave의 tier: "4x" 블록만 있었다면 Carol과 마찬가지로 분당 $0.20까지 허용됐을 거예요. 그의 cap: "strict" 블록은 병렬로 청구되고 대신 그를 $0.02로 제한해요. 따라서 나중에 더 높은 티어로 옮겨도 그의 상한은 절대 올라가지 않아요. cap 레이블을 제거해야만 상한이 올라가요.

Grace(tier: "4x", groups: "suspended")는 예산에 도달하지도 못해요:

GRACE_ACCESS_TOKEN=$(curl -X POST "$ISSUER_URL/oauth/token" \
     --no-progress-meter --fail-with-body  \
     -H "Content-Type: application/x-www-form-urlencoded" \
     -d "grant_type=client_credentials" \
     -d "client_id=$GRACE_CLIENT_ID" \
     -d "client_secret=$GRACE_CLIENT_SECRET" \
     -d "scope=budgets-access"  | jq -r ".access_token"
)
curl -X POST "$KONNECT_PROXY_URL/v1/chat/completions" \
     --no-progress-meter --fail-with-body  \
     -H "Content-Type: application/json"\
     -H "Authorization: Bearer $GRACE_ACCESS_TOKEN" \
     --json '{
       "model": "budget-chat",
       "messages": [
         {
           "role": "user",
           "content": "What is DNS?"
         }
       ]
     }'

요청은 403 Forbidden으로 실패해요. Grace의 티어와 무관하게, 요청이 budget-limits에 도달하기 전에 access.acls가 suspended 그룹 때문에 거부해요.

이 요청이 403을 반환하지 않는다면, budget-identity가 아직 kong_groups를 Kong이 인식하는 ACL 그룹으로 투영하고 있지 않은 것이 원인일 가능성이 높아요. consumer_groups_claim과 upstream_headers_names가 실제로 적용됐는지 확인하고(위의 FAQ 참조), 재시도하기 전에 kongctl apply 이후 변경 사항이 데이터 플레인에 도달할 때까지 몇 초 기다리세요.

Observability에서 사용량 보기

AI Gateway는 Gen AI 메트릭을 Observability로 내보내요. 템플릿으로 만든 대시보드에서 확인해 보세요:

  1. Konnect 사이드바에서 Observability를 클릭하세요.
  2. Observability 사이드바에서 Dashboards를 클릭하세요.
  3. Create dashboard 드롭다운 메뉴에서 "Create from template"을 선택하세요.
  4. AI Gateway Template을 클릭하세요.
  5. Use template을 클릭하세요.

Gen AI model usage count 타일에는 gpt-4o-mini 사용 2회와 gpt-4o 사용 1회가 보여요. 이는 Carol과 Dave의 budget-chat 요청, 그리고 Carol의 budget-chat-premium 요청을 반영한 거예요. Grace의 요청은 모델에 도달하지 않으므로 여기에는 나타나지 않아요.

정리

AI Gateway 리소스 정리

이 가이드에서 생성한 모든 AI Gateway 리소스를 정리하려면 다음을 실행하세요:

curl -Ls https://get.konghq.com/ai | bash -s -- -d

Kong Identity 리소스 정리

curl -X DELETE "https://us.api.konghq.com/v1/auth-servers/$AUTH_SERVER_ID?force=true" \
     --no-progress-meter --fail-with-body  \
     -H "Authorization: Bearer $KONNECT_TOKEN"\
     -H "Content-Type: application/json"

FAQ

  • 티어가 셋이고 상한(cap)이 하나 있는데 AI Consumer Group은 왜 두 개만 존재하나요? 티어와 상한은 AI Consumer Group 엔티티가 아니라, AI Auth Strategy가 토큰에서 투영해 내는 헤더에서 매칭돼요. 따라서 티어가 바뀌어도 AI Gateway에는 아무것도 기록되지 않아요. access.acls가 실제 그룹 이름과 비교하기 때문에 매칭되는 AI Consumer Group이 필요한 것은 contractors와 suspended뿐이에요.

  • budget-identity의 config 필드에 consumer_groups_claim과 upstream_headers_claims가 포함되는 이유는 무엇인가요? 이 필드들은 토큰의 kong_groups, budget_tier, budget_org, budget_cap 클레임을 x-budget-* 요청 헤더와 AI Gateway가 검사하는 ACL 그룹에 투영해요. kongctl(1.12.0 이상)은 이를 AI Auth Strategy의 config 일부로 직접 적용하므로 별도의 단계가 필요 없어요.

  • 해석 가능한 클레임이 전혀 없는 호출자에게는 어떤 일이 발생하나요? consumer_groups_optional: true는 그룹 클레임이 누락되었거나 인식되지 않아도 요청이 실패하지 않는다는 뜻이에요. 그러면 subject 헤더만으로 매칭되는 fail-safe 정책이 해당 호출자를 무제한으로 두는 대신 최상위 티어와 동일한 상한으로 묶어요.

  • fail-safe 정책은 왜 중요한가요? AI Rate Limiting Advanced Policy는 아무것도 매칭되지 않을 때 폴백할 강제 수단이 없어요. 업스트림의 표현식이 리터럴 기본값 대신 null을 반환하는 일이 생기면 티어 헤더가 사라지고, 매칭되는 정책이 없는 호출자는 전혀 레이트 리밋되지 않아요. fail-safe 정책은 subject 헤더만으로 매칭되므로 항상 적용되고, 해당 호출자를 무제한으로 두는 대신 최상위 티어의 상한으로 제한해요.

관련 리소스

더 알아보기 (Learn more)

  • 이 페이지가 속한 시리즈의 전체 흐름과 이전 단계인 Kong Identity 인증 서버 설정을 확인할 수 있어요 — Enforce tiered AI budgets with Kong Identity
  • Kong Identity 발급 토큰을 검증하고 클레임을 헤더로 내보내는 엔티티의 문서예요 — AI Auth Strategy
  • standard와 premium 두 모델을 구성할 때 사용하는 AI Model 엔티티를 설명해요 — AI Model
  • 계층별로 호출자를 묶고 접근을 거부할 때 쓰이는 AI Consumer Group 개념을 다뤄요 — AI Consumer Groups
  • 계층별 상한과 조직 공유 풀, 개인 한도를 거는 정책의 청구 방식을 설명해요 — AI Rate Limiting Advanced Policy