

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# 애플리케이션에서 ApplyGuardrail API 사용
<a name="guardrails-use-independent-api"></a>

가드레일은 사용 사례에 맞게 사용자 지정되고 책임 있는 AI 정책에 부합하는 생성형 AI 애플리케이션에 대한 보호 기능을 구현하는 데 사용됩니다. 가드레일을 사용하면 거부된 주제를 구성하고, 유해한 콘텐츠를 필터링하고, 민감한 정보를 제거할 수 있습니다.

`ApplyGuardrail` API를 사용하면 파운데이션 모델을 간접적으로 호출하지 않고도 사전 구성된 Amazon Bedrock Guardrails를 사용하여 텍스트를 평가할 수 있습니다.

`ApplyGuardrail` API의 기능은 다음과 같습니다.
+ **콘텐츠 확인** - 텍스트 입력 또는 출력을 `ApplyGuardrail` API로 전송하여 정의된 주제 회피 규칙, 콘텐츠 필터, PII 감지기, 단어 차단 목록과 비교할 수 있습니다. 사용자 입력과 FM 생성 출력을 독립적으로 평가할 수 있습니다.
+ **유연한 배포** - 결과를 처리하거나 사용자에게 제공하기 전에 애플리케이션 흐름의 모든 위치에 `ApplyGuardrail` API를 통합하여 데이터를 검증할 수 있습니다. 예를 들어 RAG 애플리케이션을 사용하는 경우, 이제 최종 응답 생성까지 기다리는 대신 검색을 수행하기 전에 사용자 입력을 평가할 수 있습니다.
+ **파운데이션 모델과 분리** - `ApplyGuardrail` API는 기본 모델과 분리됩니다. 이제 파운데이션 모델을 간접적으로 호출하지 않고도 가드레일을 사용할 수 있습니다. 평가 결과를 사용하여 생성형 AI 애플리케이션에 대한 환경을 설계할 수 있습니다.

**Topics**
+ [애플리케이션 흐름에서 ApplyGuardrail API 직접 호출](#guardrails-use-independent-api-call)
+ [ApplyGuardrail과 함께 사용할 가드레일 지정](#guardrails-use-indepedent-api-call-configure)
+ [ApplyGuardrail 사용 사례 예제](#guardrails-use-independent-api-call-message)
+ [ApplyGuardrail 응답에서 전체 출력 반환](#guardrails-use-return-full-assessment)

## 애플리케이션 흐름에서 ApplyGuardrail API 직접 호출
<a name="guardrails-use-independent-api-call"></a>

이 요청을 통해 고객은 정의된 가드레일을 사용하여 보호해야 하는 모든 콘텐츠를 전달할 수 있습니다. 평가할 콘텐츠가 사용자로부터 온 경우(일반적으로 LLM에 대한 입력 프롬프트), 소스 필드를 `INPUT`으로 설정해야 합니다. 모델 출력 가드레일을 강제 적용해야 하는 경우(일반적으로 LLM 응답), 소스를 `OUTPUT`으로 설정해야 합니다.

## ApplyGuardrail과 함께 사용할 가드레일 지정
<a name="guardrails-use-indepedent-api-call-configure"></a>

`ApplyGuardrail`을 사용할 때 사용할 가드레일의 `guardrailIdentifier` 및 `guardrailVersion`을 지정합니다. 가드레일에 대한 추적을 활성화하여 가드레일이 차단한 콘텐츠에 대한 정보를 확인할 수도 있습니다.

------
#### [ ApplyGuardrail API request ]

```
POST /guardrail/{guardrailIdentifier}/version/{guardrailVersion}/apply HTTP/1.1
{
    "source": "INPUT" | "OUTPUT",
    "content": [{
        "text": {
            "text": "string",
        }
    }, ]
}
```

------
#### [ ApplyGuardrail API response ]

```
{
    "usage": { 
          "topicPolicyUnits": "integer",
          "contentPolicyUnits": "integer",
          "wordPolicyUnits": "integer",
          "sensitiveInformationPolicyUnits": "integer",
          "sensitiveInformationPolicyFreeUnits": "integer",
          "contextualGroundingPolicyUnits": "integer"
     },
    "action": "GUARDRAIL_INTERVENED" | "NONE",
    "output": [
            // if guardrail intervened and output is masked we return request in same format
            // with masking
            // if guardrail intervened and blocked, output is a single text with canned message
            // if guardrail did not intervene, output is empty array
            {
                "text": "string",
            },
    ],
    "assessments": [{
        "topicPolicy": {
                "topics": [{
                    "name": "string",
                    "type": "DENY",
                    "action": "BLOCKED",
                }]
            },
            "contentPolicy": {
                "filters": [{
                    "type": "INSULTS | HATE | SEXUAL | VIOLENCE | MISCONDUCT |PROMPT_ATTACK",
                    "confidence": "NONE" | "LOW" | "MEDIUM" | "HIGH",
                    "filterStrength": "NONE" | "LOW" | "MEDIUM" | "HIGH",
                "action": "BLOCKED"
                }]
            },
            "wordPolicy": {
                "customWords": [{
                    "match": "string",
                    "action": "BLOCKED"
                }],
                "managedWordLists": [{
                    "match": "string",
                    "type": "PROFANITY",
                    "action": "BLOCKED"
                }]
            },
            "sensitiveInformationPolicy": {
                "piiEntities": [{
                    // for all types see: https://docs.aws.amazon.com/bedrock/latest/APIReference/API_GuardrailPiiEntityConfig.html#bedrock-Type-GuardrailPiiEntityConfig-type
                    "type": "ADDRESS" | "AGE" | ...,
                    "match": "string",
                    "action": "BLOCKED" | "ANONYMIZED"
                }],
                "regexes": [{
                    "name": "string",
                    "regex": "string",
                    "match": "string",
                    "action": "BLOCKED" | "ANONYMIZED"
                }],
            "contextualGroundingPolicy": {
                 "filters": [{
                   "type": "GROUNDING | RELEVANCE",
                   "threshold": "double",
                   "score": "double",
                   "action": "BLOCKED | NONE"
                 }]
            },
            "invocationMetrics": {
                "guardrailProcessingLatency": "integer",
                "usage": {
                    "topicPolicyUnits": "integer",
                    "contentPolicyUnits": "integer",
                    "wordPolicyUnits": "integer",
                    "sensitiveInformationPolicyUnits": "integer",
                    "sensitiveInformationPolicyFreeUnits": "integer",
                    "contextualGroundingPolicyUnits": "integer"
                },
                "guardrailCoverage": {
                    "textCharacters": {
                        "guarded":"integer",
                        "total": "integer"
                    }
                }
            }
        },
        "guardrailCoverage": {
            "textCharacters": {
                "guarded": "integer",
                "total": "integer"
            }
        }
    ]
}
```

------

## ApplyGuardrail 사용 사례 예제
<a name="guardrails-use-independent-api-call-message"></a>

`ApplyGuardrail` 요청의 출력은 전달된 콘텐츠에서 수행한 작업 가드레일에 따라 달라집니다.
+ 콘텐츠가 마스킹 처리된 곳에만 가드레일이 개입된 경우, 정확한 콘텐츠가 마스킹이 적용된 상태로 반환됩니다.
+ 가드레일이 개입하여 요청 콘텐츠를 차단한 경우 출력 필드는 단일 텍스트가 되며, 이 텍스트는 가드레일 구성을 기반으로 미리 구성된 메시지입니다.
+ 요청 콘텐츠에 가드레일 작업을 수행하지 않은 경우 출력 배열이 비어 있습니다.

------
#### [ Guardrails takes no action ]

**요청 예제**

```
{
    "source": "OUTPUT",
    "content": [
        "text": {
            "text": "Hi, my name is Zaid. Which car brand is reliable?"
        }
    ]
}
```

**응답 예제**

```
{
    "usage": {
        "topicPolicyUnitsProcessed": 1,
        "contentPolicyUnitsProcessed": 1,
        "wordPolicyUnitsProcessed": 0,
        "sensitiveInformationPolicyFreeUnits": 0
    },
    "action": "NONE",
    "outputs": [],
    "assessments": [{}]
}
```

------
#### [ Guardrails blocks content ]

**응답 예제**

```
{
    "usage": {
        "topicPolicyUnitsProcessed": 1,
        "contentPolicyUnitsProcessed": 1,
        "wordPolicyUnitsProcessed": 0,
        "sensitiveInformationPolicyFreeUnits": 0
    },
    "action": "GUARDRAIL_INTERVENED",
    "outputs": [{
        "text": "Configured guardrail canned message (i.e., can't respond)"
    }],
    "assessments": [{
        "topicPolicy": {
            "topics": [{
                "name": "Cars",
                "type": "DENY",
                "action": "BLOCKED"
            }]
        },
        "sensitiveInformationPolicy": {
            "piiEntities": [{
                "type": "NAME",
                "match": "ZAID",
                "action": "ANONYMIZED"
            }],
            "regexes": []
        }
    }]
}
```

------
#### [ Guardrails masks content ]

**응답 예제**

가드레일은 `ZAID` 이름을 마스킹하여 개입합니다.

```
{
    "usage": {
        "topicPolicyUnitsProcessed": 1,
        "contentPolicyUnitsProcessed": 1,
        "wordPolicyUnitsProcessed": 0,
        "sensitiveInformationPolicyFreeUnits": 0
    },
    "action": "GUARDRAIL_INTERVENED",
    "outputs": [{
            "text": "Hi, my name is {NAME}. Which car brand is reliable?"
        },
        {
            "text": "Hello {NAME}, ABC Cars are reliable ..."
        }
    ],
    "assessments": [{
        "sensitiveInformationPolicy": {
            "piiEntities": [{
                "type": "NAME",
                "match": "ZAID",
                "action": "ANONYMIZED"
            }],
            "regexes": []
        }
    }]
}
```

------
#### [ AWS CLI example ]

**입력 예제**

```
aws bedrock-runtime apply-guardrail \
    --cli-input-json '{
        "guardrailIdentifier": "someGuardrailId",
        "guardrailVersion": "DRAFT",
        "source": "INPUT",
        "content": [
            {
                "text": {
                    "text": "How should I invest for my retirement? I want to be able to generate $5,000 a month"
                }
            }
        ]
    }' \
    --region us-east-1 \
    --output json
```

**출력 예제(콘텐츠 차단)**

```
{
    "usage": {
        "topicPolicyUnits": 1,
        "contentPolicyUnits": 1,
        "wordPolicyUnits": 1,
        "sensitiveInformationPolicyUnits": 1,
        "sensitiveInformationPolicyFreeUnits": 0
    },
    "action": "GUARDRAIL_INTERVENED",
    "outputs": [
        {
            "text": "I apologize, but I am not able to provide fiduciary advice. ="
        }
    ],
    "assessments": [
        {
            "topicPolicy": {
                "topics": [
                    {
                        "name": "Fiduciary Advice",
                        "type": "DENY",
                        "action": "BLOCKED"
                    }
                ]
            }
        }
    ]
}
```

------

## ApplyGuardrail 응답에서 전체 출력 반환
<a name="guardrails-use-return-full-assessment"></a>

콘텐츠는 가드레일 구성을 위반하는 경우 감지된 것으로 간주됩니다. 예를 들어, 근거 또는 관련성 점수가 해당 임계값보다 작으면 컨텍스트 근거가 감지된 것으로 간주됩니다.

기본적으로 [ApplyGuardrail](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_ApplyGuardrail.html) 작업은 감지된 콘텐츠만 응답으로 반환합니다. `FULL` 값으로 `outputScope` 필드를 지정하여 전체 출력을 반환할 수 있습니다. 이 경우 응답에는 향상된 디버깅을 위해 감지되지 않은 항목도 포함됩니다.

추적을 활성화된 전체 옵션으로 설정하여 `Invoke` 및 `Converse` 작업에서 이와 동일한 동작을 구성할 수 있습니다.

**참고**  
민감한 정보 필터의 단어 필터 또는 정규식에는 전체 출력 범위가 적용되지 않습니다. 개인 식별 정보(PII)를 감지할 수 있는 필터가 있는 민감한 정보를 포함하여 다른 모든 필터링 정책에 적용됩니다.