Pular para o conteúdo principal

rótulo Schemas

Os esquemas de rótulo definem as perguntas específicas que os especialistas de domínio respondem ao rótulo de traços existentes no aplicativo Review. Eles estruturam o processo de coleta de feedback, garantindo informações consistentes e relevantes para a avaliação do seu aplicativo GenAI.

nota

Os esquemas de rótulo só se aplicam ao uso do Review App para rótulo de traces existentes e não ao uso do Review App para testar novas versões de aplicativos na UI de bate-papo.

Como funcionam os esquemas de rótulos

Ao criar uma rótulo Session, o senhor a associa a um ou mais rótulo Schemas. Cada esquema representa um Feedback ou Expectation Assessment que é anexado a um rastreamento do MLflow.

Os esquemas controlam:

  • A pergunta mostrada aos revisores
  • O método de entrada (dropdown, caixa de texto, etc.)
  • Regras e restrições de validação
  • Instruções e comentários opcionais
important

rótulo Os nomes dos esquemas devem ser exclusivos em cada MLflow Experiment. Você não pode ter dois esquemas com o mesmo nome no mesmo experimento, mas você pode reutilizar nomes de esquemas em experimentos diferentes.

rótulo Schemas para casos de uso comuns

MLflow fornece nomes de esquema predefinidos para os juízes LLM integrados que usam expectativas. Você pode criar esquemas personalizados usando esses nomes para garantir compatibilidade com a funcionalidade de avaliação integrada.

  • Trabalha com o juiz das Diretrizes

    • GUIDELINES : Coleta as instruções ideais que o aplicativo GenAI deve seguir para uma solicitação
  • Trabalha com o juiz de correção

    • EXPECTED_FACTS : Coleta declarações factuais que devem ser incluídas para serem corretas
    • EXPECTED_RESPONSE : Coleta a resposta completa e verdadeira

Criação de esquemas para casos de uso comuns

Python
import mlflow.genai.label_schemas as schemas
from mlflow.genai.label_schemas import LabelSchemaType, InputTextList, InputText

# Schema for collecting expected facts
expected_facts_schema = schemas.create_label_schema(
name=schemas.EXPECTED_FACTS,
type=LabelSchemaType.EXPECTATION,
title="Expected facts",
input=InputTextList(max_length_each=1000),
instruction="Please provide a list of facts that you expect to see in a correct response.",
overwrite=True
)

# Schema for collecting guidelines
guidelines_schema = schemas.create_label_schema(
name=schemas.GUIDELINES,
type=LabelSchemaType.EXPECTATION,
title="Guidelines",
input=InputTextList(max_length_each=500),
instruction="Please provide guidelines that the model's output is expected to adhere to.",
overwrite=True
)

# Schema for collecting expected response
expected_response_schema = schemas.create_label_schema(
name=schemas.EXPECTED_RESPONSE,
type=LabelSchemaType.EXPECTATION,
title="Expected response",
input=InputText(),
instruction="Please provide a correct agent response.",
overwrite=True
)

Criação de esquemas de rótulos personalizados

Crie esquemas personalizados para coletar feedback específico para seu domínio. O senhor pode criar esquemas por meio da UI do MLflow ou programaticamente usando o SDK.

nota

Lembre-se de que os nomes dos esquemas devem ser exclusivos na experiência atual do MLflow. Escolha nomes descritivos que indiquem claramente a finalidade de cada esquema.

Criação de esquemas por meio da interface do usuário

Navegue até o rótulo tab na UI MLflow para criar esquemas visualmente. Isso fornece uma interface intuitiva para definir perguntas, tipos de entrada e regras de validação sem escrever código.

feedback humano

Criando esquemas programaticamente

Todos os esquemas exigem um nome, tipo, título e especificação de entrada.

Criação de esquema básico

Python
import mlflow.genai.label_schemas as schemas
from mlflow.genai.label_schemas import InputCategorical, InputText

# Create a feedback schema for rating response quality
quality_schema = schemas.create_label_schema(
name="response_quality",
type="feedback",
title="How would you rate the overall quality of this response?",
input=InputCategorical(options=["Poor", "Fair", "Good", "Excellent"]),
instruction="Consider accuracy, relevance, and helpfulness when rating."
)

Tipos de esquema

Escolha entre dois tipos de esquema:

  • feedback : avaliações subjetivas, como avaliações, preferências ou opiniões
  • expectation : Verdades básicas objetivas, como respostas corretas ou comportamento esperado
Python
import mlflow.genai.label_schemas as schemas
from mlflow.genai.label_schemas import InputCategorical, InputTextList

# Feedback schema for subjective assessment
tone_schema = schemas.create_label_schema(
name="response_tone",
type="feedback",
title="Is the response tone appropriate for the context?",
input=InputCategorical(options=["Too formal", "Just right", "Too casual"]),
enable_comment=True # Allow additional comments
)

# Expectation schema for ground truth
facts_schema = schemas.create_label_schema(
name="required_facts",
type="expectation",
title="What facts must be included in a correct response?",
input=InputTextList(max_count=5, max_length_each=200),
instruction="List key facts that any correct response must contain."
)

Gerenciando esquemas de rótulos

Use as funções do SDK para gerenciar seus esquemas de forma programática:

Recuperando esquemas

Python
import mlflow.genai.label_schemas as schemas

# Get an existing schema
schema = schemas.get_label_schema("response_quality")
print(f"Schema: {schema.name}")
print(f"Type: {schema.type}")
print(f"Title: {schema.title}")

Atualizando esquemas

Python
import mlflow.genai.label_schemas as schemas
from mlflow.genai.label_schemas import InputCategorical

# Update by recreating with overwrite=True
updated_schema = schemas.create_label_schema(
name="response_quality",
type="feedback",
title="Rate the response quality (updated question)",
input=InputCategorical(options=["Excellent", "Good", "Fair", "Poor", "Very Poor"]),
instruction="Updated: Focus on factual accuracy above all else.",
overwrite=True # Replace existing schema
)

Excluindo esquemas

Python
import mlflow.genai.label_schemas as schemas

# Remove a schema that's no longer needed
schemas.delete_label_schema("old_schema_name")

Tipos de entrada para esquemas personalizados

O MLflow é compatível com cinco tipos de entrada para coletar diferentes tipos de feedback:

Use para opções mutuamente exclusivas:

Python
from mlflow.genai.label_schemas import InputCategorical

# Rating scale
rating_input = InputCategorical(
options=["1 - Poor", "2 - Below Average", "3 - Average", "4 - Good", "5 - Excellent"]
)

# Binary choice
safety_input = InputCategorical(options=["Safe", "Unsafe"])

# Multiple categories
error_type_input = InputCategorical(
options=["Factual Error", "Logical Error", "Formatting Error", "No Error"]
)

Use quando várias opções puderem ser selecionadas:

Python
from mlflow.genai.label_schemas import InputCategoricalList

# Multiple error types can be present
errors_input = InputCategoricalList(
options=[
"Factual inaccuracy",
"Missing context",
"Inappropriate tone",
"Formatting issues",
"Off-topic content"
]
)

# Multiple content types
content_input = InputCategoricalList(
options=["Technical details", "Examples", "References", "Code samples"]
)

Texto em formato livre (InputText)

Use para respostas abertas:

Python
from mlflow.genai.label_schemas import InputText

# General feedback
feedback_input = InputText(max_length=500)

# Specific improvement suggestions
improvement_input = InputText(
max_length=200 # Limit length for focused feedback
)

# Short answers
summary_input = InputText(max_length=100)

Várias entradas de texto (InputTextList)

Use para coletar listas de itens de texto:

Python
from mlflow.genai.label_schemas import InputTextList

# List of factual errors
errors_input = InputTextList(
max_count=10, # Maximum 10 errors
max_length_each=150 # Each error description limited to 150 chars
)

# Missing information
missing_input = InputTextList(
max_count=5,
max_length_each=200
)

# Improvement suggestions
suggestions_input = InputTextList(max_count=3) # No length limit per item

Entrada numérica (InputNumeric)

Use para classificações ou pontuações numéricas:

Python
from mlflow.genai.label_schemas import InputNumeric

# Confidence score
confidence_input = InputNumeric(
min_value=0.0,
max_value=1.0
)

# Rating scale
rating_input = InputNumeric(
min_value=1,
max_value=10
)

# Cost estimate
cost_input = InputNumeric(min_value=0) # No maximum limit

Exemplos completos

Avaliação do atendimento ao cliente

Aqui está um exemplo abrangente para avaliar as respostas do atendimento ao cliente:

Python
import mlflow.genai.label_schemas as schemas
from mlflow.genai.label_schemas import (
InputCategorical,
InputCategoricalList,
InputText,
InputTextList,
InputNumeric
)

# Overall quality rating
quality_schema = schemas.create_label_schema(
name="service_quality",
type="feedback",
title="Rate the overall quality of this customer service response",
input=InputCategorical(options=["Excellent", "Good", "Average", "Poor", "Very Poor"]),
instruction="Consider helpfulness, accuracy, and professionalism.",
enable_comment=True
)

# Issues identification
issues_schema = schemas.create_label_schema(
name="response_issues",
type="feedback",
title="What issues are present in this response? (Select all that apply)",
input=InputCategoricalList(options=[
"Factually incorrect information",
"Unprofessional tone",
"Doesn't address the question",
"Too vague or generic",
"Contains harmful content",
"No issues identified"
]),
instruction="Select all issues you identify. Choose 'No issues identified' if the response is problem-free."
)

# Expected resolution steps
resolution_schema = schemas.create_label_schema(
name="expected_resolution",
type="expectation",
title="What steps should be included in the ideal resolution?",
input=InputTextList(max_count=5, max_length_each=200),
instruction="List the key steps a customer service rep should take to properly resolve this issue."
)

# Confidence in assessment
confidence_schema = schemas.create_label_schema(
name="assessment_confidence",
type="feedback",
title="How confident are you in your assessment?",
input=InputNumeric(min_value=1, max_value=10),
instruction="Rate from 1 (not confident) to 10 (very confident)"
)

Revisão de informações médicas

Exemplo de avaliação de respostas de informações médicas:

Python
import mlflow.genai.label_schemas as schemas
from mlflow.genai.label_schemas import InputCategorical, InputTextList, InputNumeric

# Safety assessment
safety_schema = schemas.create_label_schema(
name="medical_safety",
type="feedback",
title="Is this medical information safe and appropriate?",
input=InputCategorical(options=[
"Safe - appropriate general information",
"Concerning - may mislead patients",
"Dangerous - could cause harm if followed"
]),
instruction="Assess whether the information could be safely consumed by patients."
)

# Required disclaimers
disclaimers_schema = schemas.create_label_schema(
name="required_disclaimers",
type="expectation",
title="What medical disclaimers should be included?",
input=InputTextList(max_count=3, max_length_each=300),
instruction="List disclaimers that should be present (e.g., 'consult your doctor', 'not professional medical advice')."
)

# Accuracy of medical facts
accuracy_schema = schemas.create_label_schema(
name="medical_accuracy",
type="feedback",
title="Rate the factual accuracy of the medical information",
input=InputNumeric(min_value=0, max_value=100),
instruction="Score from 0 (completely inaccurate) to 100 (completely accurate)"
)

Integração com o rótulo Sessions

Depois de criado, use seus esquemas no rótulo Sessions:

Python
import mlflow.genai.label_schemas as schemas

# Schemas are automatically available when creating labeling sessions
# The Review App will present questions based on your schema definitions

# Example: Using schemas in a session (conceptual - actual session creation
# happens through the Review App UI or other APIs)
session_schemas = [
"service_quality", # Your custom schema
"response_issues", # Your custom schema
schemas.EXPECTED_FACTS # Built-in schema
]

Melhores práticas

Design do esquema

  • Títulos claros : escreva perguntas como instruções claras e específicas
  • Instruções úteis : Fornecer contexto aos revisores do guia
  • Restrições apropriadas : defina limites razoáveis para o tamanho do texto e o número de listas
  • Opções lógicas : para entradas categóricas, garanta que as opções sejam mutuamente exclusivas e abrangentes

Gerenciamento de esquemas

  • Nomeação consistente : use nomes descritivos e consistentes em seus esquemas
  • Controle de versão : ao atualizar esquemas, considere o impacto nas sessões existentes
  • Limpar : Exclua esquemas não utilizados para manter seu workspace organizado

Seleção do tipo de entrada

  • Use InputCategorical para classificações ou classificações padronizadas
  • Use InputCategoricalList quando houver várias questões ou recurso
  • Use InputText para obter explicações detalhadas ou feedback personalizado
  • Use InputTextList para listas estruturadas de itens
  • Use InputNumeric para obter pontuações precisas ou classificações de confiança

Próximas etapas