Guardrails API

Checks Guardrails API พร้อมใช้งานในเวอร์ชันอัลฟ่าในเวอร์ชันตัวอย่างส่วนตัวแล้ว ขอสิทธิ์เข้าถึงเวอร์ชันตัวอย่างแบบส่วนตัวโดยใช้แบบฟอร์มแสดงความสนใจ

Guardrails API เป็น API ที่ช่วยให้คุณตรวจสอบได้ว่าข้อความอาจเป็นอันตรายหรือไม่ปลอดภัยหรือไม่ คุณสามารถใช้ API นี้ในแอปพลิเคชัน GenAI เพื่อป้องกันไม่ให้ ผู้ใช้เห็นเนื้อหาที่อาจเป็นอันตราย

วิธีใช้การป้องกัน

ใช้แนวทางป้องกันการตรวจสอบกับอินพุตและเอาต์พุตของ Gen AI เพื่อตรวจหาและลด การมีอยู่ของข้อความที่ละเมิดนโยบาย

แผนภาพแสดงวิธีใช้ Guardrails API ในแอป Gen AI

เหตุใดจึงควรใช้การควบคุม

บางครั้ง LLM อาจสร้างเนื้อหาที่อาจเป็นอันตรายหรือไม่เหมาะสม การผสานรวม Guardrails API เข้ากับแอปพลิเคชัน GenAI เป็นสิ่งสำคัญอย่างยิ่งในการ รับประกันการใช้โมเดลภาษาขนาดใหญ่ (LLM) อย่างมีความรับผิดชอบและปลอดภัยยิ่งขึ้น โดยจะช่วยลดความเสี่ยงที่เกี่ยวข้องกับเนื้อหาที่สร้างขึ้นด้วยการกรองผลลัพธ์ที่อาจเป็นอันตรายในวงกว้าง ซึ่งรวมถึงภาษาที่ไม่เหมาะสม ข้อสังเกตที่เลือกปฏิบัติ และเนื้อหาที่อาจก่อให้เกิดอันตราย ซึ่งไม่เพียงปกป้องผู้ใช้ของคุณ แต่ยังช่วยรักษาชื่อเสียงของแอปพลิเคชันและ เสริมสร้างความไว้วางใจในหมู่ผู้ชมด้วย การให้ความสำคัญกับความปลอดภัยและความรับผิดชอบ Guardrails ช่วยให้คุณสร้างแอปพลิเคชัน GenAI ที่ทั้งเป็นนวัตกรรม และปลอดภัยยิ่งขึ้น

เริ่มต้นใช้งาน

คู่มือนี้จะแสดงวิธีการใช้ Guardrails API เพื่อตรวจหาและ กรองเนื้อหาที่ไม่เหมาะสมในแอปพลิเคชันของคุณ API มี นโยบายที่ผ่านการฝึกมาก่อนหลากหลายรูปแบบซึ่งสามารถระบุเนื้อหาประเภทต่างๆ ที่อาจเป็นอันตราย เช่น วาจาสร้างความเกลียดชัง ความรุนแรง และเนื้อหาเกี่ยวกับเรื่องเพศอย่างโจ่งแจ้ง นอกจากนี้ คุณยังปรับแต่งลักษณะการทำงานของ API ได้โดยการตั้งค่าเกณฑ์สำหรับแต่ละนโยบาย

ข้อกำหนดเบื้องต้น

  1. ได้รับการอนุมัติโปรเจ็กต์ Google Cloud สำหรับการแสดงตัวอย่างแบบส่วนตัวของ Checks AI Safety หากยังไม่ได้ขอสิทธิ์เข้าถึง ให้ขอสิทธิ์โดยใช้แบบฟอร์มแสดงความสนใจ
  2. เปิดใช้ Checks API
  3. ตรวจสอบว่าคุณส่งคำขอที่ได้รับอนุญาตได้โดยใช้คำแนะนำเกี่ยวกับการให้สิทธิ์

นโยบายที่รองรับ

ชื่อนโยบาย คำอธิบายนโยบาย ค่า Enum ของ API ประเภทนโยบาย
เนื้อหาที่ไม่ปลอดภัย เนื้อหาที่อำนวยความสะดวก ส่งเสริม หรือเปิดให้เข้าถึงสินค้า บริการ และกิจกรรมที่เป็นอันตราย DANGEROUS_CONTENT
การขอและท่อง PII เนื้อหาที่ขอหรือเปิดเผยข้อมูลส่วนบุคคลหรือข้อมูลที่มีความละเอียดอ่อนของบุคคล PII_SOLICITING_RECITING
การล่วงละเมิด เนื้อหาที่เป็นอันตราย ข่มขู่ กลั่นแกล้ง หรือละเมิดต่อบุคคลอื่น HARASSMENT
เกี่ยวกับเรื่องเพศอย่างโจ่งแจ้ง เนื้อหาที่มีลักษณะเกี่ยวกับเรื่องเพศอย่างโจ่งแจ้ง SEXUALLY_EXPLICIT
วาจาสร้างความเกลียดชัง เนื้อหาที่โดยทั่วไปถือเป็นวาจาสร้างความเกลียดชัง HATE_SPEECH
ข้อมูลทางการแพทย์ ไม่อนุญาตให้แสดงเนื้อหาที่สนับสนุน ส่งเสริม หรือเปิดโอกาสให้เข้าถึงคำแนะนำหรือคำชี้แนะทางการแพทย์ที่เป็นอันตราย MEDICAL_INFO
ความรุนแรงและเนื้อหาน่าหวาดกลัว เนื้อหาที่มีคำอธิบายความรุนแรงและ/หรือภาพคราบเลือดที่สมจริงโดยไม่มีเหตุอันควร VIOLENCE_AND_GORE
ลามกอนาจารและหยาบคาย เราไม่อนุญาตให้แสดงเนื้อหาที่มีภาษาหยาบคาย หยาบโลน หรือไม่เหมาะสม OBSCENITY_AND_PROFANITY

ข้อมูลโค้ด

Python

ติดตั้งไคลเอ็นต์ Python ของ Google API โดยเรียกใช้ 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

ติดตั้งไคลเอ็นต์ Go ของ Checks API โดยเรียกใช้ 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

หมายเหตุ: ตัวอย่างนี้ใช้oauth2l เครื่องมือ CLI

แทนที่ YOUR_GCP_PROJECT_ID ด้วยรหัสโปรเจ็กต์ Google Cloud ที่ได้รับสิทธิ์เข้าถึง 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",
      },
    ]
  }'

ตัวอย่างการตอบกลับ

  {
    "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"
      }
    ]
  }

กรณีการใช้งาน

คุณสามารถผสานรวม Guardrails API เข้ากับแอปพลิเคชัน LLM ได้หลายวิธี โดยขึ้นอยู่กับความต้องการเฉพาะและความเสี่ยงที่ยอมรับได้ ตัวอย่างกรณีการใช้งานที่พบบ่อยมีดังนี้

ไม่มีการแทรกแซงโดยใช้แนวทาง - การบันทึก

ในกรณีนี้ ระบบจะใช้ Guardrails API โดยไม่มีการเปลี่ยนแปลงลักษณะการทำงานของแอป อย่างไรก็ตาม ระบบจะบันทึกการละเมิดนโยบายที่อาจเกิดขึ้นเพื่อวัตถุประสงค์ในการตรวจสอบ และการตรวจสอบ นอกจากนี้ยังสามารถใช้ข้อมูลนี้เพื่อระบุ ความเสี่ยงด้านความปลอดภัยที่อาจเกิดขึ้นกับ 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)
  }

การป้องกันไม่ให้เกิดการละเมิดถูกบล็อกตามนโยบาย

ในตัวอย่างนี้ Guardrails API จะบล็อกอินพุตของผู้ใช้และคำตอบของโมเดลที่ไม่ปลอดภัย โดยจะตรวจสอบทั้ง 2 อย่างกับนโยบายด้านความปลอดภัยที่กำหนดไว้ล่วงหน้า (เช่น วาจาสร้างความเกลียดชัง เนื้อหาที่เป็นอันตราย) ซึ่งจะช่วยป้องกันไม่ให้ AI สร้างเอาต์พุตที่อาจเป็นอันตรายและ ปกป้องผู้ใช้จากการพบเนื้อหาที่ไม่เหมาะสม

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)
  }

สตรีมเอาต์พุต LLM ไปยัง Guardrails

ในตัวอย่างต่อไปนี้ เราจะสตรีมเอาต์พุตจาก LLM ไปยัง Guardrails API ซึ่งใช้เพื่อลดเวลาในการตอบสนองที่ผู้ใช้รับรู้ได้ แนวทางนี้อาจทำให้เกิดผลลบลวงเนื่องจากบริบทไม่สมบูรณ์ ดังนั้นเอาต์พุตของ LLM จึงต้องมีบริบทเพียงพอเพื่อให้ Guardrails ประเมินได้อย่างถูกต้องก่อนที่จะเรียกใช้ API

การเรียกใช้ขอบเขตแบบซิงโครนัส

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
        }
      }
    }
  }

การเรียกใช้ขอบเขตแบบอะซิงโครนัส

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
        }
      }
    }
  }

คำถามที่พบบ่อย

ฉันควรทำอย่างไรหากใช้ API ของ Guardrails จนถึงโควต้าที่กำหนดแล้ว

หากต้องการขอเพิ่มโควต้า ให้ส่งอีเมลคำขอไปที่ checks-support@google.com โปรดระบุข้อมูลต่อไปนี้ในอีเมล

  • หมายเลขโปรเจ็กต์ Google Cloud: หมายเลขนี้ช่วยให้เราระบุบัญชีของคุณได้อย่างรวดเร็ว
  • รายละเอียดเกี่ยวกับกรณีการใช้งาน: อธิบายวิธีที่คุณใช้ Guardrails API
  • จำนวนโควต้าที่ต้องการ: ระบุจำนวนโควต้าเพิ่มเติมที่คุณต้องการ