Guardrails API

Checks Guardrails API hiện có phiên bản alpha trong bản dùng thử riêng tư. Yêu cầu quyền truy cập vào Bản dùng thử riêng tư bằng biểu mẫu bày tỏ sự quan tâm của chúng tôi.

Guardrails API là một API cho phép bạn kiểm tra xem văn bản có khả năng gây hại hoặc không an toàn hay không. Bạn có thể sử dụng API này trong ứng dụng AI tạo sinh để ngăn người dùng tiếp xúc với nội dung có khả năng gây hại.

Cách sử dụng các biện pháp bảo vệ

Sử dụng Checks Guardrails (Các quy định bảo vệ của tính năng Kiểm tra) cho dữ liệu đầu vào và đầu ra của AI tạo sinh để phát hiện và giảm thiểu sự xuất hiện của văn bản vi phạm chính sách của bạn.

Sơ đồ minh hoạ cách sử dụng Guardrails API trong ứng dụng AI tạo sinh

Tại sao nên sử dụng Guardrails?

Đôi khi, LLM có thể tạo ra nội dung có khả năng gây hại hoặc không phù hợp. Việc tích hợp Guardrails API vào ứng dụng AI tạo sinh là rất quan trọng để đảm bảo việc sử dụng các mô hình ngôn ngữ lớn (LLM) một cách có trách nhiệm và an toàn hơn. Tính năng này giúp bạn giảm thiểu các rủi ro liên quan đến nội dung do AI tạo bằng cách lọc ra nhiều kết quả có khả năng gây hại, bao gồm cả ngôn từ không phù hợp, nhận xét phân biệt đối xử và nội dung có thể tạo điều kiện cho hành vi gây hại. Điều này không chỉ bảo vệ người dùng mà còn bảo vệ danh tiếng của ứng dụng và củng cố niềm tin của khán giả. Bằng cách ưu tiên sự an toàn và trách nhiệm, các Rào chắn giúp bạn xây dựng các ứng dụng AI tạo sinh vừa sáng tạo vừa an toàn hơn.

Bắt đầu

Hướng dẫn này cung cấp hướng dẫn về cách sử dụng Guardrails API để phát hiện và lọc nội dung không phù hợp trong các ứng dụng của bạn. API này cung cấp nhiều chính sách được huấn luyện trước có thể xác định nhiều loại nội dung có khả năng gây hại, chẳng hạn như lời nói hận thù, nội dung bạo lực và nội dung khiêu dâm. Bạn cũng có thể tuỳ chỉnh hành vi của API bằng cách đặt ngưỡng cho từng chính sách.

Điều kiện tiên quyết

  1. Dự án Google Cloud của bạn phải được phê duyệt để tham gia chương trình dùng thử riêng tư Checks AI Safety. Nếu chưa, hãy yêu cầu quyền truy cập bằng cách sử dụng biểu mẫu thể hiện sự quan tâm của chúng tôi.
  2. Bật Checks API.
  3. Đảm bảo bạn có thể gửi các yêu cầu được uỷ quyền bằng cách sử dụng Hướng dẫn uỷ quyền của chúng tôi.

Các chính sách được hỗ trợ

Tên chính sách Nội dung mô tả chính sách Giá trị enum API cho loại chính sách
Nội dung nguy hiểm Nội dung hỗ trợ, quảng bá hoặc cho phép truy cập vào hàng hoá, dịch vụ và hoạt động gây hại. DANGEROUS_CONTENT
Gạ gẫm và đọc to thông tin nhận dạng cá nhân (PII) Nội dung yêu cầu hoặc tiết lộ thông tin cá nhân nhạy cảm hoặc dữ liệu của một cá nhân. PII_SOLICITING_RECITING
Quấy rối Nội dung ác ý, hăm doạ, bắt nạt hoặc lăng mạ một hoặc nhiều cá nhân khác. HARASSMENT
Khiêu dâm Nội dung khiêu dâm. SEXUALLY_EXPLICIT
Lời nói hận thù Nội dung thường được coi là lời nói hận thù. HATE_SPEECH
Thông tin y tế Chúng tôi nghiêm cấm nội dung hỗ trợ, cổ xuý hoặc tạo điều kiện tiếp cận lời khuyên hoặc hướng dẫn y tế gây hại. MEDICAL_INFO
Nội dung bạo lực và đẫm máu Nội dung có phần mô tả bạo lực và/hoặc cảnh đẫm máu một cách vô cớ. VIOLENCE_AND_GORE
Nội dung khiêu dâm và thô tục Chúng tôi nghiêm cấm nội dung chứa ngôn từ thô tục, tục tĩu hoặc phản cảm. OBSCENITY_AND_PROFANITY

Đoạn mã

Python

Cài đặt ứng dụng Google API Python bằng cách chạy pip install google-api-python-client.


  import logging
  from google.oauth2 import service_account
  from googleapiclient.discovery import build

  SECRET_FILE_PATH = 'path/to/your/secret.json'

  credentials = service_account.Credentials.from_service_account_file(
      SECRET_FILE_PATH, scopes=['https://www.googleapis.com/auth/checks']
  )

  service = build('checks', 'v1alpha', credentials=credentials)

  request = service.aisafety().classifyContent(
      body={
          'input': {
              'textInput': {
                  'content': 'Mix, bake, cool, frost, and enjoy.',
                  'languageCode': 'en',
              }
          },
          'policies': [
              {'policyType': 'DANGEROUS_CONTENT'}
          ],  # Default Checks-defined threshold is used
      }
  )

  response = request.execute()

  for policy_result in response['policyResults']:
    logging.warning(
        'Policy: %s, Score: %s, Violation result: %s',
        policy_result['policyType'],
        policy_result['score'],
        policy_result['violationResult'],
    )

Go

Cài đặt Ứng dụng Go của Checks API bằng cách chạy go get google.golang.org/api/checks/v1alpha.


  package main

  import (
    "context"
    "log/slog"

    checks "google.golang.org/api/checks/v1alpha"
    option "google.golang.org/api/option"
  )

  const credsFilePath = "path/to/your/secret.json"

  func main() {
    ctx := context.Background()
    checksService, err := checks.NewService(
      ctx,
      option.WithEndpoint("https://checks.googleapis.com"),
      option.WithCredentialsFile(credsFilePath),
      option.WithScopes("https://www.googleapis.com/auth/checks"),
    )
    if err != nil {
      // Handle error
    }

    req := &checks.GoogleChecksAisafetyV1alphaClassifyContentRequest{
      Input: &checks.GoogleChecksAisafetyV1alphaClassifyContentRequestInputContent{
        TextInput: &checks.GoogleChecksAisafetyV1alphaTextInput{
          Content:      "Mix, bake, cool, frost, and enjoy.",
          LanguageCode: "en",
        },
      },
      Policies: []*checks.GoogleChecksAisafetyV1alphaClassifyContentRequestPolicyConfig{
        {PolicyType: "DANGEROUS_CONTENT"}, // Default Checks-defined threshold is used
      },
    }

    classificationResults, err := checksService.Aisafety.ClassifyContent(req).Do()
    if err != nil {
      // Handle error
    }

    for _, policy := range classificationResults.PolicyResults {
      slog.Info("Checks Guardrails violation: ", "Policy", policy.PolicyType, "Score", policy.Score, "Violation Result", policy.ViolationResult)
    }
  }

REST

Lưu ý: Ví dụ này sử dụng công cụ CLI oauth2l.

Thay YOUR_GCP_PROJECT_ID bằng mã dự án Google Cloud đã được cấp quyền truy cập vào Guardrails API.

  curl -X POST   https://checks.googleapis.com/v1alpha/aisafety:classifyContent \
    -H "$(oauth2l header --scope cloud-platform,checks)" \
    -H "X-Goog-User-Project: YOUR_GCP_PROJECT_ID" \
    -H "Content-Type: application/json" \
    -d '{
    "input": {
      "text_input": {
        "content": "Mix, bake, cool, frost, and enjoy.",
        "language_code": "en"
      }
    },
    "policies": [
      {
        "policy_type": "HARASSMENT",
        "threshold": "0.5"
      },
      {
        "policy_type": "DANGEROUS_CONTENT",
      },
    ]
  }'

Phản hồi mẫu

  {
    "policyResults": [
      {
        "policyType": "HARASSMENT",
        "score": 0.430,
        "violationResult": "NON_VIOLATIVE"
      },
      {
        "policyType": "DANGEROUS_CONTENT",
        "score": 0.764,
        "violationResult": "VIOLATIVE"
      },
      {
        "policyType": "OBSCENITY_AND_PROFANITY",
        "score": 0.876,
        "violationResult": "VIOLATIVE"
      },
      {
        "policyType": "SEXUALLY_EXPLICIT",
        "score": 0.197,
        "violationResult": "NON_VIOLATIVE"
      },
      {
        "policyType": "HATE_SPEECH",
        "score": 0.45,
        "violationResult": "NON_VIOLATIVE"
      },
      {
        "policyType": "MEDICAL_INFO",
        "score": 0.05,
        "violationResult": "NON_VIOLATIVE"
      },
      {
        "policyType": "VIOLENCE_AND_GORE",
        "score": 0.964,
        "violationResult": "VIOLATIVE"
      },
      {
        "policyType": "PII_SOLICITING_RECITING",
        "score": 0.0009,
        "violationResult": "NON_VIOLATIVE"
      }
    ]
  }

Trường hợp sử dụng

Bạn có thể tích hợp Guardrails API vào ứng dụng LLM theo nhiều cách, tuỳ thuộc vào nhu cầu cụ thể và khả năng chấp nhận rủi ro của bạn. Sau đây là một số ví dụ về các trường hợp sử dụng phổ biến:

Không có sự can thiệp của hàng rào bảo vệ – Ghi nhật ký

Trong trường hợp này, Guardrails API được dùng mà không có bất kỳ thay đổi nào đối với hành vi của ứng dụng. Tuy nhiên, các trường hợp có khả năng vi phạm chính sách đang được ghi lại cho mục đích giám sát và kiểm tra. Thông tin này có thể được dùng để xác định các rủi ro tiềm ẩn về độ an toàn của LLM.

Python

  import logging
  from google.oauth2 import service_account
  from googleapiclient.discovery import build

  # Checks API configuration
  class ChecksConfig:

    def __init__(self, scope, creds_file_path):
      self.scope = scope
      self.creds_file_path = creds_file_path

  my_checks_config = ChecksConfig(
      scope='https://www.googleapis.com/auth/checks',
      creds_file_path='path/to/your/secret.json',
  )

  def new_checks_service(config):
    """Creates a new Checks API service."""

    credentials = service_account.Credentials.from_service_account_file(
        config.creds_file_path, scopes=[config.scope]
    )

    service = build('checks', 'v1alpha', credentials=credentials)
    return service

  def fetch_checks_violation_results(content, context=''):
    """Fetches violation results from the Checks API."""

    service = new_checks_service(my_checks_config)

    request = service.aisafety().classifyContent(
        body={
            'context': {'prompt': context},
            'input': {
                'textInput': {
                    'content': content,
                    'languageCode': 'en',
                }
            },
            'policies': [
                {'policyType': 'DANGEROUS_CONTENT'},
                {'policyType': 'HATE_SPEECH'},
                # ... add more policies
            ],
        }
    )

    response = request.execute()
    return response

  def fetch_user_prompt():
    """Imitates retrieving the input prompt from the user."""
    return 'How do I bake a cake?'

  def fetch_llm_response(prompt):
    """Imitates the call to an LLM endpoint."""
    return 'Mix, bake, cool, frost, enjoy.'

  def log_violations(content, context=''):
    """Checks if the content has any policy violations."""

    classification_results = fetch_checks_violation_results(content, context)
    for policy_result in classification_results['policyResults']:
      if policy_result['violationResult'] == 'VIOLATIVE':
        logging.warning(
            'Policy: %s, Score: %s, Violation result: %s',
            policy_result['policyType'],
            policy_result['score'],
            policy_result['violationResult'],
        )
    return False

  if __name__ == '__main__':
    user_prompt = fetch_user_prompt()
    log_violations(user_prompt)
    llm_response = fetch_llm_response(user_prompt)

    log_violations(llm_response, user_prompt)
    print(llm_response)

Go

  package main

  import (
    "context"
    "fmt"
    "log/slog"

    checks "google.golang.org/api/checks/v1alpha"
    option "google.golang.org/api/option"
  )

  type checksConfig struct {
    scope            string
    credsFilePath    string
    endpoint         string
  }

  var myChecksConfig = checksConfig{
    scope:            "https://www.googleapis.com/auth/checks",
    credsFilePath:    "path/to/your/secret.json",
    endpoint:         "https://checks.googleapis.com",
  }

  func newChecksService(ctx context.Context, cfg checksConfig) (*checks.Service, error) {
    return checks.NewService(
      ctx,
      option.WithEndpoint(cfg.endpoint),
      option.WithCredentialsFile(cfg.credsFilePath),
      option.WithScopes(cfg.scope),
    )
  }

  func fetchChecksViolationResults(ctx context.Context, content string, context string) (*checks.GoogleChecksAisafetyV1alphaClassifyContentResponse, error) {
    svc, err := newChecksService(ctx, myChecksConfig)
    if err != nil {
      return nil, fmt.Errorf("failed to create checks service: %w", err)
    }

    req := &checks.GoogleChecksAisafetyV1alphaClassifyContentRequest{
      Context: &checks.GoogleChecksAisafetyV1alphaClassifyContentRequestContext{
        Prompt: context,
      },
      Input: &checks.GoogleChecksAisafetyV1alphaClassifyContentRequestInputContent{
        TextInput: &checks.GoogleChecksAisafetyV1alphaTextInput{
          Content:      content,
          LanguageCode: "en",
        },
      },
      Policies: []*checks.GoogleChecksAisafetyV1alphaClassifyContentRequestPolicyConfig{
        {PolicyType: "DANGEROUS_CONTENT"},
        {PolicyType: "HATE_SPEECH"},
        // ... add more policies
      },
    }

    response, err := svc.Aisafety.ClassifyContent(req).Do()
    if err != nil {
      return nil, fmt.Errorf("failed to classify content: %w", err)
    }

    return response, nil
  }

  // Imitates retrieving the input prompt from the user.
  func fetchUserPrompt() string {
    return "How do I bake a cake?"
  }

  // Imitates the call to an LLM endpoint.
  func fetchLLMResponse(prompt string) string {
    return "Mix, bake, cool, frost, enjoy."
  }

  func logViolations(ctx context.Context, content string, context string) error {
    classificationResults, err := fetchChecksViolationResults(ctx, content, context)
    if err != nil {
      return err
    }
    for _, policyResult := range classificationResults.PolicyResults {
      if policyResult.ViolationResult == "VIOLATIVE" {
        slog.Warn("Checks Guardrails violation: ", "Policy", policyResult.PolicyType, "Score", policyResult.Score, "Violation Result", policyResult.ViolationResult)
      }
    }
    return nil
  }

  func main() {
    ctx := context.Background()

    userPrompt := fetchUserPrompt()
    err := logViolations(ctx, userPrompt, "")
    if err != nil {
      // Handle error
    }

    llmResponse := fetchLLMResponse(userPrompt)
    err = logViolations(ctx, llmResponse, userPrompt)
    if err != nil {
      // Handle error
    }

    fmt.Println(llmResponse)
  }

Rào chắn bị chặn dựa trên một chính sách

Trong ví dụ này, Guardrails API chặn hoạt động đầu vào không an toàn của người dùng và các phản hồi của mô hình. Công cụ này kiểm tra cả hai loại nội dung dựa trên các chính sách an toàn được xác định trước (ví dụ: lời nói hận thù, nội dung nguy hiểm). Việc này giúp ngăn AI tạo ra những kết quả có thể gây hại và bảo vệ người dùng khỏi việc gặp phải nội dung không phù hợp.

Python

  from google.oauth2 import service_account
  from googleapiclient.discovery import build

  # Checks API configuration
  class ChecksConfig:

    def __init__(self, scope, creds_file_path, default_threshold):
      self.scope = scope
      self.creds_file_path = creds_file_path
      self.default_threshold = default_threshold

  my_checks_config = ChecksConfig(
      scope='https://www.googleapis.com/auth/checks',
      creds_file_path='path/to/your/secret.json',
      default_threshold=0.6,
  )

  def new_checks_service(config):
    """Creates a new Checks API service."""

    credentials = service_account.Credentials.from_service_account_file(
        config.creds_file_path, scopes=[config.scope]
    )

    service = build('checks', 'v1alpha', credentials=credentials)
    return service

  def fetch_checks_violation_results(content, context=''):
    """Fetches violation results from the Checks API."""

    service = new_checks_service(my_checks_config)

    request = service.aisafety().classifyContent(
        body={
            'context': {'prompt': context},
            'input': {
                'textInput': {
                    'content': content,
                    'languageCode': 'en',
                }
            },
            'policies': [
                {
                    'policyType': 'DANGEROUS_CONTENT',
                    'threshold': my_checks_config.default_threshold,
                },
                {'policyType': 'HATE_SPEECH'},
                # ... add more policies
            ],
        }
    )

    response = request.execute()
    return response

  def fetch_user_prompt():
    """Imitates retrieving the input prompt from the user."""
    return 'How do I bake a cake?'

  def fetch_llm_response(prompt):
    """Imitates the call to an LLM endpoint."""
    return 'Mix, bake, cool, frost, enjoy.'

  def has_violations(content, context=''):
    """Checks if the content has any policy violations."""

    classification_results = fetch_checks_violation_results(content, context)
    for policy_result in classification_results['policyResults']:
      if policy_result['violationResult'] == 'VIOLATIVE':
        return True
    return False

  if __name__ == '__main__':
    user_prompt = fetch_user_prompt()
    if has_violations(user_prompt):
      print("Sorry, I can't help you with this request.")
    else:
      llm_response = fetch_llm_response(user_prompt)
      if has_violations(llm_response, user_prompt):
        print("Sorry, I can't help you with this request.")
      else:
        print(llm_response)

Go

  package main

  import (
    "context"
    "fmt"

    checks "google.golang.org/api/checks/v1alpha"
    option "google.golang.org/api/option"
  )

  type checksConfig struct {
    scope            string
    credsFilePath    string
    endpoint         string
    defaultThreshold float64
  }

  var myChecksConfig = checksConfig{
    scope:            "https://www.googleapis.com/auth/checks",
    credsFilePath:    "path/to/your/secret.json",
    endpoint:         "https://checks.googleapis.com",
    defaultThreshold: 0.6,
  }

  func newChecksService(ctx context.Context, cfg checksConfig) (*checks.Service, error) {
    return checks.NewService(
      ctx,
      option.WithEndpoint(cfg.endpoint),
      option.WithCredentialsFile(cfg.credsFilePath),
      option.WithScopes(cfg.scope),
    )
  }

  func fetchChecksViolationResults(ctx context.Context, content string, context string) (*checks.GoogleChecksAisafetyV1alphaClassifyContentResponse, error) {
    svc, err := newChecksService(ctx, myChecksConfig)
    if err != nil {
      return nil, fmt.Errorf("failed to create checks service: %w", err)
    }

    req := &checks.GoogleChecksAisafetyV1alphaClassifyContentRequest{
      Context: &checks.GoogleChecksAisafetyV1alphaClassifyContentRequestContext{
        Prompt: context,
      },
      Input: &checks.GoogleChecksAisafetyV1alphaClassifyContentRequestInputContent{
        TextInput: &checks.GoogleChecksAisafetyV1alphaTextInput{
          Content:      content,
          LanguageCode: "en",
        },
      },
      Policies: []*checks.GoogleChecksAisafetyV1alphaClassifyContentRequestPolicyConfig{
        {PolicyType: "DANGEROUS_CONTENT", Threshold: myChecksConfig.defaultThreshold},
        {PolicyType: "HATE_SPEECH"}, // default Checks-defined threshold is used
        // ... add more policies
      },
    }

    response, err := svc.Aisafety.ClassifyContent(req).Do()
    if err != nil {
      return nil, fmt.Errorf("failed to classify content: %w", err)
    }

    return response, nil
  }

  // Imitates retrieving the input prompt from the user.
  func fetchUserPrompt() string {
    return "How do I bake a cake?"
  }

  // Imitates the call to an LLM endpoint.
  func fetchLLMResponse(prompt string) string {
    return "Mix, bake, cool, frost, enjoy."
  }

  func hasViolations(ctx context.Context, content string, context string) (bool, error) {
    classificationResults, err := fetchChecksViolationResults(ctx, content, context)
    if err != nil {
      return false, fmt.Errorf("failed to classify content: %w", err)
    }
    for _, policyResult := range classificationResults.PolicyResults {
      if policyResult.ViolationResult == "VIOLATIVE" {
        return true, nil
      }
    }
    return false, nil
  }

  func main() {
    ctx := context.Background()

    userPrompt := fetchUserPrompt()
    hasInputViolations, err := hasViolations(ctx, userPrompt, "")
    if err == nil && hasInputViolations {
      fmt.Println("Sorry, I can't help you with this request.")
      return
    }

    llmResponse := fetchLLMResponse(userPrompt)
    hasOutputViolations, err := hasViolations(ctx, llmResponse, userPrompt)
    if err == nil && hasOutputViolations {
      fmt.Println("Sorry, I can't help you with this request.")
      return
    }

    fmt.Println(llmResponse)
  }

Truyền trực tuyến kết quả đầu ra của LLM đến Guardrails

Trong các ví dụ sau, chúng ta sẽ truyền trực tuyến đầu ra từ một LLM đến Guardrails API. Bạn có thể dùng cách này để giảm độ trễ mà người dùng cảm nhận được. Phương pháp này có thể đưa ra kết quả dương tính giả do bối cảnh không đầy đủ. Vì vậy, điều quan trọng là đầu ra của LLM phải có đủ bối cảnh để Guardrails đánh giá chính xác trước khi gọi API.

Lệnh gọi đồng bộ cho quy định

Python

  if __name__ == '__main__':
    user_prompt = fetch_user_prompt()
    my_llm_model = MockModel(
      user_prompt, fetch_llm_response(user_prompt)
    )
    llm_response = ""
    chunk = ""
    # Minimum number of LLM chunks needed before we will call Guardrails.
    contextThreshold = 2
    while not my_llm_model.finished:
      chunk = my_llm_model.next_chunk()
      llm_response += str(chunk)
      if my_llm_model.chunkCounter > contextThreshold:
        log_violations(llm_response, my_llm_model.userPrompt)

Go

  func main() {
    ctx := context.Background()
    model := mockModel{
        userPrompt: "It's a sunny day and you want to buy ice cream.",
        response:   []string{"What a lovely day", "to get some ice cream.", "is the shop open?"},
    }
    // Minimum number of LLM chunks needed before we will call Guardrails.
    const contextThreshold = 2
    var llmResponse string
    for !model.finished {
      chunk := model.nextChunk()
      llmResponse += chunk + " "
      if model.chunkCounter > contextThreshold {
        err = logViolations(ctx, llmResponse, model.userPrompt)
        if err != nil {
            // Handle error
        }
      }
    }
  }

Lệnh gọi không đồng bộ cho các quy định

Python

  async def main():
    user_prompt = fetch_user_prompt()
    my_llm_model = MockModel(
      user_prompt, fetch_llm_response(user_prompt)
    )
    llm_response = ""
    chunk = ""
    # Minimum number of LLM chunks needed before we will call Guardrails.
    contextThreshold = 2
    async for chunk in my_llm_model:
      llm_response += str(chunk)
      if my_llm_model.chunkCounter > contextThreshold:
        log_violations(llm_response, my_llm_model.userPrompt)
    asyncio.run(main())

Go

  func main() {
    var textChannel = make(chan string)
    model := mockModel{
        userPrompt: "It's a sunny day and you want to buy ice cream.",
        response:   []string{"What a lovely day", "to get some ice cream.", "is the shop open?"},
    }
    var llmResponse string

    // Minimum number of LLM chunks needed before we will call Guardrails.
    const contextThreshold = 2
    go model.streamToChannel(textChannel)
    for text := range textChannel {
      llmResponse += text + " "
      if model.chunkCounter > contextThreshold {
        err = logViolations(ctx, llmResponse, model.userPrompt)
        if err != nil {
          // Handle error
        }
      }
    }
  }

Câu hỏi thường gặp

Tôi nên làm gì nếu đã đạt đến hạn mức cho Guardrails API?

Để yêu cầu tăng hạn mức, hãy gửi yêu cầu của bạn đến email checks-support@google.com. Hãy cung cấp những thông tin sau trong email của bạn:

  • Số dự án của bạn trên Google Cloud: Thông tin này giúp chúng tôi nhanh chóng xác định tài khoản của bạn.
  • Thông tin chi tiết về trường hợp sử dụng của bạn: Giải thích cách bạn đang sử dụng Guardrails API.
  • Số lượng hạn mức mong muốn: Cho biết bạn cần thêm bao nhiêu hạn mức.