모델 재정의 시도가 있는지 각 요청을 검사하는 AI 게이트웨이
지원 어시스턴트의 사용자는 무엇이든 입력할 수 있으며, 입력 중 일부는 모델이 받은 지시를 무시하도록 만들려고 시도합니다. 모델 앞에 있는 게이트웨이는 모든 요청을 먼저 가드로 보낼 수 있습니다. 가드는 학습된 분류기에 요청이 그러한 시도인지 묻고, 그렇다면 거부하며, 나머지는 모델로 전달하는 서비스입니다. 이 워크스페이스는 이 구성을 Kubernetes 매니페스트로 컴파일합니다. 게이트웨이, 가드, 그리고 가드의 분류기가 실행되는 탐지기입니다.
이를 요청하는 Feature는 core/prompt-injection-shield입니다. 이 Feature가 하는 일은
이름에서 짐작되는 것보다 좁으며, 이 페이지는 하는 일만큼이나 하지 않는 일에도 많은 분량을
할애합니다. 판정은 확률적 분류기의 판정이고, 일부 공격을 놓치며 일부 정당한 요청을 거부하고,
회피 가능한 것으로 알려져 있으며, 모델의 응답도, 도구 호출 인수도,
이미지도 판단하지 않습니다. 이는 여러 통제 수단 가운데 하나입니다.
이 워크스페이스는 자체 카탈로그 엔티티를 작성하지 않습니다. 여기 있는 세 개의 엔티티 파일, 즉 Aggregate, Manifest, Release가 누구든 작성하는 내용의 전부입니다.
구성되는 내용
| 인스턴스 | 카탈로그 Component | 여기서의 역할 |
|---|---|---|
router | core/gateway/litellm | AI 게이트웨이: 모델 맵에 입력된 하나의 별칭 assistant가 가드 뒤에 있는 모델을 가리킵니다 |
guard | core/security/nemo-guardrails | 모델 경로에 있는 NVIDIA NeMo Guardrails 서버로, 각 채팅 요청을 검사하고 허용한 요청을 모델로 전달합니다 |
detector | core/security/trustyai-huggingface-detector | 가드가 질의하는 분류기 서비스로, 기본 프롬프트 인젝션 분류기를 실행합니다 |
uses 엣지가 두 개 있습니다. 게이트웨이의 guard 소켓에서 가드로, 그리고 가드의
detector 소켓에서 탐지기로 이어지는 엣지입니다. Feature 연결도 두 개 있습니다. 게이트웨이에는
실드인 shield가 sensitivity: standard로 연결되고, 가드에는 가드가 모델 API에 제시하는 자격 증명인 upstream_key가 연결됩니다.
예제 생성하기
아래 명령으로 이 예제를 빌드하거나, AI 어시스턴트에게 대신 빌드하게 할 수 있습니다.
예제 이름을 딴 새 폴더에 예제를 씁니다:
aggrega scaffold --example ai-gateway-prompt-injection-shield그런 다음 이어서 실행할 명령을 출력합니다. 첫 번째 명령은 새 폴더로 이동합니다:
cd ai-gateway-prompt-injection-shield빌드
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이 워크스페이스는 .aggrega-config.yaml이 지정하는 기본 레지스트리에서 카탈로그 엔터티를 해석합니다. shield의 실현은 컴파일러에도 카탈로그에도 포함되지 않은 플러그인 하나를 실행하는데, 이는 게이트웨이 구성 단계인 pipeline-step/litellm-gateway-config이며, 해석 과정에서 default_registry가 지정하는 레지스트리인 hub.aggrega.ai에서 가져옵니다.
빌드는 다음을 출력하며, <workspace>는 이 예제의 폴더를 나타냅니다.
[… omitted: a line reporting on the gateway configuration step's plugin, a warning that the upstream_key credential's 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: 10 files written to <workspace>/dist카탈로그가 guard와 detector의 이미지를 지정하지 않으므로 Release가 이를 지정합니다. 각 Component의 infra.image는 기본값이 없는 필수 설정이며, Component에서 그 옆의 주석이 그 이유를 설명하고 동작이 검증된 빌드를 명시합니다. release.yaml의 두 값은 직접 운영하는 빌드의 사본을, 직접 관리하는 레지스트리로 미러링한 것을 위한 자리 표시자입니다. 빌드는 그 자리에 있는 문자열을 그대로 전달하므로, 배포하기 전에 두 값을 모두 교체합니다.
AI 어시스턴트 사용
Aggrega 도구로 설정한 AI 어시스턴트도 같은 작업을 할 수 있습니다. 다음 프롬프트를 붙여 넣으십시오.
Aggrega 도구만 사용하고 폴더를 직접 만들지 마십시오. 워크스페이스 폴더에 아직 `ai-gateway-prompt-injection-shield` 폴더가 없으면 `example`에 `ai-gateway-prompt-injection-shield`를 지정하고 `dir` 없이 `scaffold` 도구를 한 번 호출하십시오. 그러면 예제가 새 `ai-gateway-prompt-injection-shield` 폴더에 쓰입니다. 그런 다음 `workspace_root`에 `ai-gateway-prompt-injection-shield`, `release`에 `release.yaml`, `auto_pull`에 true, `write`에 true를 지정하여 `build` 도구를 호출하십시오. 빌드가 어떤 파일을 썼는지 알려 주십시오. 파일은 `ai-gateway-prompt-injection-shield/dist/` 아래에 있습니다.렌더링된 트리
dist/helm/├── detector-default-service.yaml├── detector-deployment.yaml├── guard--upstream-zukey--guard-secret-guard-upstream-key.yaml├── guard-default-service.yaml├── guard-deployment.yaml├── guard/│ └── nemo-guardrails-config.configmap.yaml├── router-default-service.yaml├── router-deployment.yaml└── router/ ├── litellm-gateway-config/ │ └── configmap.yaml └── request-guard/ └── request-guard.yamlshield는 자체 파일을 가져오지 않습니다. shield가 하는 일은 gateway의 구성에 기록됩니다.
게이트웨이가 읽는 라우트
게이트웨이의 구성 본문, 즉
dist/helm/router/litellm-gateway-config/configmap.yaml의 config.yaml 키입니다:
model_list: - model_name: assistant litellm_params: model: openai/gpt-4o-mini api_base: "http://guard-default:8000/v1" api_key: "the-guard-holds-the-upstream-credential"litellm_settings: callbacks: - /etc/litellm-request-guard/request_field_filter.filtercallback_settings: request_field_filter.router-shield: policies: - reason: "sends every model request through a prompt-injection guard, which checks chat completions only" served_request_types: - acompletion여기서 세 가지를 읽어 낼 수 있습니다.
모든 별칭은 가드를 향합니다. api_base는 guard 엣지에서 읽어 온, 가드가
게시하는 엔드포인트이므로, assistant에 대한 요청은 OpenAI API를 통해 가드로 가서
gpt-4o-mini를 요청합니다. 가드는 허용한 요청을 release.yaml이 upstream_endpoint에
지정한 모델 API로 전달합니다. 실드를 제거하면 항목은 이전과 똑같이 api_base 없이
작성됩니다. 별칭을 게이트웨이의 models 소켓에 연결된 모델에서 제공하지 않고
게이트웨이의 values.models에 직접 입력하는 이유가 이것입니다. 연결된 모델의 항목은
그 모델 자체의 엔드포인트와 그 연결 자체의 키로 작성되므로 요청이 가드를 거치지 않고
모델로 가게 되며, 아래에서 설명하듯 실드는 그러한 연결을 거부합니다.
게이트웨이는 모델에 대한 자격 증명을 보유하지 않습니다. 게이트웨이가 provider가
아닌 가드에 접속하므로 항목에는 키 대신 고정된 단어가 지정되며, 가드는 자체 자격 증명,
즉 upstream_key 슬롯에 연결된 자격 증명을 제시합니다. 호출자 자신의 Authorization
헤더는 모델에 도달하지 않습니다.
채팅 완성만 제공됩니다. 가드는 채팅 완성을 검사하며 completions, embeddings, responses, messages 라우트는 제공하지 않으므로, 정책은 게이트웨이의 요청 가드가 그 밖의 모든 종류의 요청을 아무것도 전달하기 전에 이유와 함께 HTTP 400으로 거부하도록 합니다:
This gateway sends every model request through a prompt-injection guard, which checks chat completions only, and it does not serve embeddings requests while it does, so the request was not forwarded. It serves chat completions requests.가드가 하는 일
가드의 구성으로, 레일 부분부터 보인
dist/helm/guard/nemo-guardrails-config.configmap.yaml의 config.yaml 키입니다.
rails: config: hf_classifier: prompt_injection: engine: fms model: "protectai/deberta-v3-base-prompt-injection-v2" base_url: "http://detector-default:8000" threshold: 0.5 blocked_labels: ["INJECTION"] input: flows: - hf classifier check input $classifier=prompt_injection일반 요청이든 스트리밍 요청이든 각 채팅 요청에 대해 가드는 최신 사용자
메시지를 탐지기에 보내고, 탐지기는 로드한 분류기로 이를 채점합니다. 탐지기가 0.5 이상으로 INJECTION을 보고하면 가드는 요청을 거부합니다.
거부된 요청에는 가드가 직접 응답하며, 메시지가 *I’m sorry, I can’t respond to that.*인 일반 completion을 반환합니다. 요청이 스트림을 요청한 경우에는 스트리밍으로 반환하며, 요청의 어떤 내용도 모델에 도달하지 않습니다.
가드가 허용한 요청은 시스템 메시지와 이전 턴을 포함하여 호출자가 보낸 그대로 모델에 도달합니다.
호출자는 요청에서 검사를 끌 수 없습니다. 가드의
구성에는 요청 본문이 무엇을 요구하든 검사를 실행하는 플로 rails.co가 포함되어 있으며, 가드는 이 하나의 구성만 실행하고 다른 구성을 지정하는 요청은 거부합니다. 이 게이트웨이에서 guardrails 필드는 게이트웨이 자체의 필드이므로
전달되지 않으며, extra_body처럼 게이트웨이가 전달하도록 구성되지 않은 필드는 거부됩니다.
하지 않는 일
- 일부 공격을 놓치고 일부 정상 요청을 거부합니다. 판정은 임계값에 대한 분류기의 점수입니다. 표현을 바꾸거나, 다른 언어로 쓰거나, 인코딩하거나 철자를 바꾼 시도는 점수가 낮게 나와 처리될 수 있고, 일반 요청은 점수가 높게 나와 거부될 수 있습니다.
- 최신 사용자 메시지만 읽습니다. 시스템 메시지, 이전 턴 또는 도구 결과에 담긴 시도는 읽히지 않은 채 모델에 도달합니다.
- 모델의 응답, 도구 호출 인수 또는 이미지는 판단하지 않습니다.
- 게이트웨이를 거치는 트래픽만 다룹니다. 모델의 주소를 직접 호출하는 워크로드는 게이트웨이를 우회합니다. 가드와 탐지기는 호출자를 인증하지 않으므로, 이들의 Service는 이를 호출하는 구성 요소를 위한 주소이며 공개할 주소가 아닙니다.
민감도
standard와 strict는 가드의 임계값 0.5와 0.001로 실행됩니다.
이 두 숫자는 탐지기의 기본 분류기를 기준으로 측정한 값이며, 이 분류기의
점수는 0에 가깝거나 1에 가깝게 나옵니다. 0.5에서 가드는 모델의 지시를 무시하게 하려는
평이한 시도를 거부합니다. 0.001에서는 그러한 시도를 leetspeak로 바꿔 쓴 경우도 거부하는데,
분류기는 이를 0.008 근처로 채점합니다. 그와 함께 분류기가 낮게 채점하지만 0에 가깝지는 않은
일부 일반 요청도 거부합니다.
임계값은 가드 자체의 값이므로, strict로 바꾸려면 두 곳을 함께
수정해야 합니다. 연결에 sensitivity: strict를, 가드의 values에 threshold: 0.001을
지정합니다. 구현은 두 값이 일치하는지 확인합니다. 구현은 가드를 볼 뿐 그 뒤의 탐지기는
보지 못하므로, 탐지기가 어떤 모델을 로드했는지 알 수 없습니다. 다른 모델을 실행하는 탐지기는
점수를 다르게 매기며, 그 임계값은 다시 측정해야 합니다.
빌드를 중단시키는 것
다음 각 경우에 빌드는 무엇을 바꿔야 하는지 알려 주는 문장을 출력합니다.
-
sensitivity와 guard의 임계값이 일치하지 않는 경우.
sensitivity: strict를 설정하고 guard를 기본값으로 둡니다.[… omitted: a line reporting on the gateway configuration step's plugin, 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 E0010] instance routernode "router": pipeline step failed[… omitted: the step, the template position and the template's own source]error calling fail: core/prompt-injection-shield attachment "shield" on "router" asks for sensitivity strict, which this realization runs as the guard's threshold 0.001, but the guard "guard" runs at 0.5; set values.threshold of "guard" to 0.001 -
guard가 연결되지 않은 경우.
guard엣지만 담고 있는 게이트웨이의uses블록을 제거하면 아무것도 렌더링되기 전에 빌드가 중단되며 소켓을 지목합니다:[… omitted: a line reporting on the gateway configuration step's plugin, 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 "prompt-injection-shield-litellm" instance "router" assertion "guard_is_wired": [… omitted: the template position and the assertion's own source]: error calling fail: assertion failed: core/prompt-injection-shield attachment "shield" on "router" needs a guard to send the gateway's model requests through, but nothing is wired to its guard socket; wire a core/security/nemo-guardrails to the guard socket of "router" -
게이트웨이의
models소켓에 모델이 연결된 경우. 그 항목은 guard를 거치지 않고 해당 모델 자체의 엔드포인트로 그 연결 자체의 키와 함께 전송됩니다. 타입이 지정된 별칭 옆에core/ai-model/openai를fast로 소켓에 연결하고 연결에 자격 증명을 둔 뒤 — 이때 게이트웨이는 두 별칭을 제공하고 하나를 게시하므로values.model: assistant를 설정하고, Release에서fast를, Manifest에서 그 Recipe를 지정합니다 — 빌드하면 아무것도 렌더링되기 전에 빌드가 중단되며 해당 연결을 지목합니다:[… omitted: a line reporting on the gateway configuration step's plugin, 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 "prompt-injection-shield-litellm" instance "router" assertion "no_wired_models": [… omitted: the template position and the assertion's own source]: error calling fail: assertion failed: core/prompt-injection-shield attachment "shield" on "router" sends every model request through the guard, which forwards it to its own upstream with its own credential, but the models socket of "router" holds fast, each sent to its own model's endpoint with its own connection's credential, past the guard; remove those connections and reach that model through the guard's upstream, or remove the shield attachment -
게이트웨이의
provider_key슬롯에 자격 증명이 있는 경우. 이 자격 증명은 guard에게만 제시되고 어떤 모델에도 제시되지 않습니다. 빌드는 대신 guard의upstream_key슬롯을 지목합니다. -
다른 guard. 소켓은 프롬프트 guard가 학습된 분류기인 어떤 component든 받아들이지만, realization은 두 sensitivity가 측정된 대상인
core/security/nemo-guardrails이외의 guard에서는 중단되며, 소켓에 두 번째 guard가 연결된 경우에도 중단됩니다. -
openai/<model>형식으로 작성되지 않은 대상은 게이트웨이가 다른 API를 통해 guard로 보내게 됩니다. -
같은 게이트웨이의
core/semantic-caching. 캐시는 맵의 별칭을 통해 각 프롬프트를 임베딩하는데, 이 요청은 임베딩 요청에 응답하지 않는 guard로 전송되므로 캐시는 아무것도 캐시하지 못합니다. -
게이트웨이의 두 번째 shield.
가드 또는 탐지기에 연결할 수 없는 경우
요청은 거부되며, 모델에는 아무것도 도달하지 않습니다. 탐지기가 중단된 경우, 가드는 일반 요청에는 내부 오류를 보고하는 완성 응답으로, 스트리밍 요청에는 텍스트가 없는 스트림으로 응답합니다. 가드가 중단된 경우, 게이트웨이는 오류로 응답합니다. 이 구성에서는 가드가 실패할 때 요청을 가드를 우회하여 보내는 부분이 없습니다.
컴파일러가 해석하지 않는 부분
컴파일러는 guard의 Service 이름과 포트를 gateway의 구성에, threshold와 detector의 주소를 guard의 구성에 문자열로 전달합니다. 컴파일러는 프롬프트를 평가하지 않고, classifier가 어떤 점수를 매길지 알지 못하며, guard, detector 또는 모델에 접속하지 않습니다. 위의 각 중단은 카탈로그 자체의 엔터티가 shield의 realization에 있는 assertion이나 파이프라인 단계의 검사로 선언한 것이며, 그중 어느 것도 트래픽에 대한 이해에 근거하지 않습니다.
응용하기
- 더 엄격하게. attachment에
sensitivity: strict를, guard에threshold: 0.001을 함께 설정합니다. - 직접 운영하는 모델. guard의
upstream_endpoint가 모델 서버의 엔드포인트를 가리키도록 하고(core/ai-model/vllm이 하나를 게시합니다), 별칭의 대상을openai/<the name that server serves>로 작성합니다. - NGINX 게이트웨이를 대신 사용.
core/gateway/nginx도 같은guard소켓을 선언하며,prompt-injection-shield-nginx는 helm과 compose 모두에서 하나뿐인 location이 upstream 대신 guard를 가리키도록 합니다. guard의upstream_endpoint를 게이트웨이의upstream소켓이 지정하는 모델로 설정합니다. 해당 location의 모든 요청은 guard로 전달되며, guard는 chat completions를 처리하고 다른 모델 경로에는 404로 응답합니다.