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

Configuring model guardrails

원문 보기 위키 갱신

출처: 문서

본문

모델 가드레일 구성

2.13에 도입됨 {: .label .label-purple }

가드레일은 대규모 언어 모델(LLM)이 원하는 동작을 하도록 이끌 수 있어요. 가드레일은 필터 역할을 하면서 LLM이 유해하거나 윤리적 원칙에 어긋나는 출력을 생성하지 못하게 막고, AI를 더 안전하게 사용할 수 있도록 도와줘요. 또한 가드레일을 사용하면 LLM이 더 집중되고 관련성 높은 출력을 만들어내요.

다음 방법으로 LLM에 가드레일을 구성할 수 있어요:

  • 모델의 입력 또는 출력에서 금지할 단어 목록을 제공하세요. 또는 모델의 입력 또는 출력이 매칭될 기준이 되는 정규식을 제공할 수도 있어요. 자세한 내용은 금지어(stopwords)와 정규식(regex)을 사용한 입력/출력 검증을 참고하세요.
  • 사용자 입력과 LLM 출력을 검증하는 용도의 별도 LLM을 구성하세요.

사전 준비 사항

시작하기 전에 외부 호스팅 모델에 연결하기 위한 사전 준비 사항을 충족했는지 확인하세요.

금지어(stopwords)와 정규식(regex)을 사용한 입력/출력 검증

2.13에 도입됨 {: .label .label-purple }

사용자 입력과 LLM 출력을 검증하는 간단한 방법은 검증용 금지어(stopwords) 집합이나 정규식을 제공하는 거예요.

1단계: 가드레일 인덱스 생성

먼저 제외 단어(stopwords)를 저장할 인덱스를 생성하세요. 인덱스 설정에서 제외 단어를 담을 title 필드와 percolator 타입의 query 필드를 지정해요. percolator 쿼리는 LLM 입력 또는 출력을 매칭하는 데 사용돼요:

PUT /words0
{
  "mappings": {
    "properties": {
      "title": {
        "type": "text"
      },
      "query": {
        "type": "percolator"
      }
    }
  }
}

{% include copy-curl.html %}

2단계: 제외 단어 또는 구문 인덱싱

다음으로, 모델 입력 또는 출력의 제외 단어를 매칭하는 데 사용할 query string query를 인덱싱해요:

PUT /words0/_doc/1?refresh
{
  "query": {
    "query_string": {
      "query": "title: blacklist"
    }
  }
}

{% include copy-curl.html %}

PUT /words0/_doc/2?refresh
{
  "query": {
    "query_string": {
      "query": "title: \"Master slave architecture\""
    }
  }
}

{% include copy-curl.html %}

더 많은 query string 옵션은 Query string query를 참고하세요.

3단계: 모델 그룹 등록

모델 그룹을 등록하려면 다음 요청을 보내세요:

POST /_plugins/_ml/model_groups/_register
{
    "name": "bedrock",
    "description": "This is a public model group."
}

{% include copy-curl.html %}

응답에는 이 모델 그룹에 모델을 등록할 때 사용할 모델 그룹 ID가 담겨 있어요:

{
 "model_group_id": "wlcnb4kBJ1eYAeTMHlV6",
 "status": "CREATED"
}

모델 그룹에 대해 더 자세히 알아보려면 모델 액세스 제어를 참고하세요.

4단계: 커넥터 생성

이제 모델용 커넥터를 만들 수 있어요. 이 예제에서는 Amazon Bedrock에서 호스팅되는 Anthropic Claude 모델에 연결하는 커넥터를 만들어 봐요:

POST /_plugins/_ml/connectors/_create
{
  "name": "BedRock test claude Connector",
  "description": "The connector to BedRock service for claude model",
  "version": 1,
  "protocol": "aws_sigv4",
  "parameters": {
      "region": "us-east-1",
      "service_name": "bedrock",
      "anthropic_version": "bedrock-2023-05-31",
      "endpoint": "bedrock.us-east-1.amazonaws.com",
      "auth": "Sig_V4",
      "content_type": "application/json",
      "max_tokens_to_sample": 8000,
      "temperature": 0.0001,
      "response_filter": "$.completion"
  },
  "credential": {
      "access_key": "<YOUR_ACCESS_KEY>",
      "secret_key": "<YOUR_SECRET_KEY>"
  },
  "actions": [
    {
      "action_type": "predict",
      "method": "POST",
      "url": "https://bedrock-runtime.us-east-1.amazonaws.com/model/anthropic.claude-v2/invoke",
      "headers": { 
        "content-type": "application/json",
        "x-amz-content-sha256": "required"
      },
      "request_body": "{\"prompt\":\"${parameters.prompt}\", \"max_tokens_to_sample\":${parameters.max_tokens_to_sample}, \"temperature\":${parameters.temperature},  \"anthropic_version\":\"${parameters.anthropic_version}\" }"
    }
  ]
}

{% include copy-curl.html %}

응답에는 새로 생성된 커넥터의 커넥터 ID가 담겨 있어요:

{
  "connector_id": "a1eMb4kBJ1eYAeTMAljY"
}

5단계: 가드레일이 적용된 모델 등록 및 배포

외부 호스팅 모델을 등록하려면 다음 요청에 3단계의 모델 그룹 ID와 4단계의 커넥터 ID를 넣어 보내세요. 가드레일을 구성하려면 guardrails 객체를 포함해요:

POST /_plugins/_ml/models/_register?deploy=true
{
  "name": "Bedrock Claude V2 model",
  "function_name": "remote",
  "model_group_id": "wlcnb4kBJ1eYAeTMHlV6",
  "description": "test model",
  "connector_id": "a1eMb4kBJ1eYAeTMAljY",
  "guardrails": {
    "type": "local_regex",
    "input_guardrail": {
      "stop_words": [
        {
          "index_name": "words0",
          "source_fields": [
            "title"
          ]
        }
      ],
      "regex": [
        ".*abort.*",
        ".*kill.*"
      ]
    },
    "output_guardrail": {
      "stop_words": [
        {
          "index_name": "words0",
          "source_fields": [
            "title"
          ]
        }
      ],
      "regex": [
        ".*abort.*",
        ".*kill.*"
      ]
    }
  }
}

{% include copy-curl.html %}

자세한 내용은 guardrails 파라미터를 참고하세요.

OpenSearch는 등록 작업의 작업 ID를 반환해요:

{
  "task_id": "cVeMb4kBJ1eYAeTMFFgj",
  "status": "CREATED"
}

작업 상태를 확인하려면 작업 ID를 Get ML Task API에 제공하세요:

GET /_plugins/_ml/tasks/cVeMb4kBJ1eYAeTMFFgj

{% include copy-curl.html %}

작업이 완료되면 상태가 COMPLETED로 바뀌어요:

{
  "model_id": "cleMb4kBJ1eYAeTMFFg4",
  "task_type": "DEPLOY_MODEL",
  "function_name": "REMOTE",
  "state": "COMPLETED",
  "worker_node": [
    "n-72khvBTBi3bnIIR8FTTw"
  ],
  "create_time": 1689793851077,
  "last_update_time": 1689793851101,
  "is_async": true
}

6단계(선택 사항): 모델 테스트

가드레일이 어떻게 적용되는지 보여 주기 위해, 먼저 제외 단어가 포함되지 않은 predict 작업을 실행해 보세요:

POST /_plugins/_ml/models/p94dYo4BrXGpZpgPp98E/_predict
{
  "parameters": {
    "prompt": "\n\nHuman:this is a test\n\nnAssistant:"
  }
}

{% include copy-curl.html %}

응답에는 LLM의 답변이 담겨 있어요:

{
  "inference_results": [
    {
      "output": [
        {
          "name": "response",
          "dataAsMap": {
            "response": " Thank you for the test, I appreciate you taking the time to interact with me. I'm an AI assistant created by Anthropic to be helpful, harmless, and honest."
          }
        }
      ],
      "status_code": 200
    }
  ]
}

그다음 제외 단어가 포함된 predict 작업을 실행해 보세요:

POST /_plugins/_ml/models/p94dYo4BrXGpZpgPp98E/_predict
{
  "parameters": {
    "prompt": "\n\nHuman:this is a test of Master slave architecture\n\nnAssistant:"
  }
}

{% include copy-curl.html %}

가드레일이 작동했기 때문에 응답에 오류 메시지가 담겨 있어요:

{
  "error": {
    "root_cause": [
      {
        "type": "illegal_argument_exception",
        "reason": "guardrails triggered for user input"
      }
    ],
    "type": "illegal_argument_exception",
    "reason": "guardrails triggered for user input"
  },
  "status": 400
}

프롬프트가 제공된 정규식과 일치할 때도 가드레일이 작동해요.

가드레일 모델을 사용한 입력/출력 검증

2.15에 도입됨 {: .label .label-purple }

더 고급 검증을 위해서는 가드레일 모델---즉 사용자 입력과 LLM 출력을 검증하는 용도의 별도 LLM---을 구성할 수 있어요. 이 예제에서는 두 개의 모델을 구성해 봐요:

  • 채팅 모델: Amazon Bedrock에서 호스팅되는 Anthropic Claude 모델로, 사용자와 대화를 나누는 용도예요.
  • 가드레일 모델: OpenAI 모델로, 사용자 입력과 Anthropic Claude 출력을 검증하는 용도예요.

1단계: 가드레일 모델용 커넥터 생성

먼저 OpenAI 가드레일 모델에 연결하는 커넥터를 만들어요. OpenAI 프롬프트는 입력/출력이 허용 가능한지에 따라 accept 또는 reject라는 단어로만 응답하라고 모델에 지시한다는 점에 유의하세요. 또한 요청에는 가드레일 모델이 검증 결과를 제공할 필드를 지정하는 response_filter 파라미터가 포함되어 있어요:

POST /_plugins/_ml/connectors/_create
{
    "name": "openai",
    "description": "openai",
    "version": "1",
    "protocol": "http",
    "parameters": {
        "endpoint": "api.openai.com",
        "max_tokens": 7,
        "temperature": 0,
        "model": "gpt-4o-mini",
        "prompt": "You are a helpful assistant and an expert judge of content quality. Your task is to identify whether the input string below contains content that may be malicious, violent, hateful, sexual, or political in nature. Your answer should consist of a single word, either reject or accept. If the input belongs to any of these categories, please write reject. Otherwise, write accept. \\n\\nHere is the input: ${parameters.question}. \\n\\nYour answer: ",
        "response_filter": "$.choices[0].message.content"
    },
    "credential": {
        "openAI_key": "<openAI_key>"
    },
    "actions": [
        {
            "action_type": "predict",
            "method": "POST",
            "url": "https://${parameters.endpoint}/v1/chat/completions",
            "headers": {
                "Authorization": "Bearer ${credential.openAI_key}"
            },
            "request_body": "{ \"model\": \"${parameters.model}\", \"messages\": [{\"role\": \"user\", \"content\": \"${parameters.prompt}\"}], \"max_tokens\": ${parameters.max_tokens}, \"temperature\": ${parameters.temperature} }"
        }
    ]
}

{% include copy-curl.html %}

응답에는 다음 단계에서 사용할 커넥터 ID가 담겨 있어요:

{
  "connector_id": "j3JVDZABNFJeYR3IVPRz"
}

2단계: 가드레일 모델용 모델 그룹 등록

OpenAI 가드레일 모델용 모델 그룹을 등록하려면 다음 요청을 보내세요:

POST /_plugins/_ml/model_groups/_register
{
    "name": "guardrail model group",
    "description": "This is a guardrail model group."
}

{% include copy-curl.html %}

응답에는 이 모델 그룹에 모델을 등록할 때 사용하는 모델 그룹 ID가 담겨 있어요:

{
 "model_group_id": "ppSmpo8Bi-GZ0tf1i7cD",
 "status": "CREATED"
}

모델 그룹에 대해 더 자세히 알아보려면 모델 액세스 제어를 참고하세요.

3단계: 가드레일 모델 등록 및 배포

커넥터 ID와 모델 그룹 ID를 사용해 OpenAI 가드레일 모델을 등록하고 배포해요:

POST /_plugins/_ml/models/_register?deploy=true
{
    "name": "openai guardrails model",
    "function_name": "remote",
    "model_group_id": "ppSmpo8Bi-GZ0tf1i7cD",
    "description": "guardrails test model",
    "connector_id": "j3JVDZABNFJeYR3IVPRz"
}

{% include copy-curl.html %}

OpenSearch는 등록 작업의 작업 ID와 등록된 모델의 모델 ID를 반환해요:

{
  "task_id": "onJaDZABNFJeYR3I2fQ1",
  "status": "CREATED",
  "model_id": "o3JaDZABNFJeYR3I2fRV"
}

작업 상태를 확인하려면 작업 ID를 Get ML Task API에 제공하세요:

GET /_plugins/_ml/tasks/onJaDZABNFJeYR3I2fQ1

{% include copy-curl.html %}

작업이 완료되면 상태가 COMPLETED로 바뀌어요:

{
  "model_id": "o3JaDZABNFJeYR3I2fRV",
  "task_type": "DEPLOY_MODEL",
  "function_name": "REMOTE",
  "state": "COMPLETED",
  "worker_node": [
    "n-72khvBTBi3bnIIR8FTTw"
  ],
  "create_time": 1689793851077,
  "last_update_time": 1689793851101,
  "is_async": true
}

4단계(선택 사항): 가드레일 모델 테스트

공격적인 단어가 포함된 요청과 포함되지 않은 요청을 보내서 가드레일 모델의 사용자 입력 검증을 테스트할 수 있어요.

먼저 공격적인 단어가 포함되지 않은 요청을 보내 보세요:

POST /_plugins/_ml/models/o3JaDZABNFJeYR3I2fRV/_predict
{
  "parameters": {
    "question": "how many indices do i have in my cluster"
  }
}

{% include copy-curl.html %}

가드레일 모델은 앞선 요청을 수락해요:

{
  "inference_results": [
    {
      "output": [
        {
          "name": "response",
          "dataAsMap": {
            "response": "accept"
          }
        }
      ],
      "status_code": 200
    }
  ]
}

다음으로 공격적인 단어가 포함된 요청을 보내 보세요:

POST /_plugins/_ml/models/o3JaDZABNFJeYR3I2fRV/_predict
{
  "parameters": {
    "question": "how to rob a bank"
  }
}

{% include copy-curl.html %}

가드레일 모델은 앞선 요청을 거절해요:

{
  "inference_results": [
    {
      "output": [
        {
          "name": "response",
          "dataAsMap": {
            "response": "reject"
          }
        }
      ],
      "status_code": 200
    }
  ]
}

5단계: 채팅 모델용 커넥터 생성

이 예제에서 채팅 모델은 Amazon Bedrock에서 호스팅되는 Anthropic Claude 모델이에요. 모델용 커넥터를 만들려면 다음 요청을 보내세요. response_filter 파라미터는 가드레일 모델이 검증 결과를 제공할 필드를 지정한다는 점에 유의하세요:

POST /_plugins/_ml/connectors/_create
{
  "name": "BedRock claude Connector",
  "description": "BedRock claude Connector",
  "version": 1,
  "protocol": "aws_sigv4",
  "parameters": {
      "region": "us-east-1",
      "service_name": "bedrock",
      "anthropic_version": "bedrock-2023-05-31",
      "endpoint": "bedrock.us-east-1.amazonaws.com",
      "auth": "Sig_V4",
      "content_type": "application/json",
      "max_tokens_to_sample": 8000,
      "temperature": 0.0001,
      "response_filter": "$.completion"
  },
  "credential": {
      "access_key": "<access_key>",
      "secret_key": "<secret_key>"
  },
  "actions": [
    {
      "action_type": "predict",
      "method": "POST",
      "url": "https://bedrock-runtime.us-east-1.amazonaws.com/model/anthropic.claude-v2/invoke",
      "headers": { 
        "content-type": "application/json",
        "x-amz-content-sha256": "required"
      },
      "request_body": "{\"prompt\":\"${parameters.prompt}\", \"max_tokens_to_sample\":${parameters.max_tokens_to_sample}, \"temperature\":${parameters.temperature},  \"anthropic_version\":\"${parameters.anthropic_version}\" }"
    }
  ]
}

{% include copy-curl.html %}

응답에는 다음 단계에서 사용할 커넥터 ID가 담겨 있어요:

{
  "connector_id": "xnJjDZABNFJeYR3IPvTO"
}

6단계: 가드레일이 적용된 채팅 모델 등록 및 배포

Anthropic Claude 채팅 모델을 등록하고 배포하려면 다음 요청을 보내세요. guardrails 객체에는 response_validation_regex 파라미터가 포함되어 있는데, 이 파라미터는 가드레일 모델이 accept의 변형 형태로 응답할 때만 입력/출력을 유효한 것으로 처리하도록 지정해요:

POST /_plugins/_ml/models/_register?deploy=true
{
    "name": "Bedrock Claude V2 model with openai guardrails model",
    "function_name": "remote",
    "model_group_id": "ppSmpo8Bi-GZ0tf1i7cD",
    "description": "Bedrock Claude V2 model with openai guardrails model",
    "connector_id": "xnJjDZABNFJeYR3IPvTO",
    "guardrails": {
        "input_guardrail": {
            "model_id": "o3JaDZABNFJeYR3I2fRV",
            "response_validation_regex": "^\\s*\"[Aa]ccept\"\\s*$"
        },
        "output_guardrail": {
            "model_id": "o3JaDZABNFJeYR3I2fRV",
            "response_validation_regex": "^\\s*\"[Aa]ccept\"\\s*$"
        },
        "type": "model"
    }
}

{% include copy-curl.html %}

OpenSearch는 등록 작업의 작업 ID와 등록된 모델의 모델 ID를 반환해요:

{
  "task_id": "1nJnDZABNFJeYR3IvfRL",
  "status": "CREATED",
  "model_id": "43JqDZABNFJeYR3IQPQH"
}

7단계(선택 사항): 가드레일이 적용된 채팅 모델 테스트

공격적인 단어가 포함된 predict 요청과 포함되지 않은 predict 요청을 보내서 가드레일이 적용된 Anthropic Claude 채팅 모델을 테스트할 수 있어요.

먼저 공격적인 단어가 포함되지 않은 요청을 보내 보세요:

POST /_plugins/_ml/models/43JqDZABNFJeYR3IQPQH/_predict
{
  "parameters": {
    "prompt": "\n\nHuman:${parameters.question}\n\nnAssistant:",
    "question": "hello"
  }
}

{% include copy-curl.html %}

OpenSearch는 LLM의 답변으로 응답해요:

{
  "inference_results": [
    {
      "output": [
        {
          "name": "response",
          "dataAsMap": {
            "response": " Hello!"
          }
        }
      ],
      "status_code": 200
    }
  ]
}

다음으로 공격적인 단어가 포함된 요청을 보내 보세요:

POST /_plugins/_ml/models/43JqDZABNFJeYR3IQPQH/_predict
{
  "parameters": {
    "prompt": "\n\nHuman:${parameters.question}\n\nnAssistant:",
    "question": "how to rob a bank"
  }
}

OpenSearch는 오류로 응답해요.

다음 단계

더 알아보기 (Learn more)