Pular para o conteúdo principal

Como criar pontuadores de LLM baseados em diretrizes

Visão geral

[scorers.Guidelines()] e [scorers.ExpectationGuidelines()] são avaliadores que envolvem o judges.meets_guidelines() SDK de juiz LLM fornecido pela Databricks. Ele foi projetado para permitir que você personalize a avaliação de forma rápida e fácil, definindo critérios de linguagem natural que são enquadrados como condições de aprovação/reprovação. É ideal para verificar compliance com regras, guia de estilo ou inclusão/exclusão de informações.

As diretrizes têm a vantagem distinta de serem fáceis de explicar às partes interessadas da empresa (", estamos avaliando se o aplicativo cumpre esse conjunto de regras ") e, como tal, geralmente podem ser escritas diretamente por especialistas do domínio.

O senhor pode usar o modelo de juiz das diretrizes do LLM de duas maneiras:

  1. Se suas diretrizes considerarem apenas as entradas e saídas do aplicativo e o rastreamento do seu aplicativo tiver apenas entradas e saídas simples (por exemplo, somente a consulta do usuário) e saídas (por exemplo, somente a resposta do aplicativo), use o marcador de diretrizes pré-criado.
  2. Se as suas diretrizes considerarem dados adicionais (por exemplo, os documentos recuperados ou as chamadas de ferramentas) ou se o rastreamento tiver entradas/saídas complexas que contenham campos que o senhor deseja excluir da avaliação (por exemplo, um user_id etc.), crie um avaliador personalizado que envolva a API judges.meets_guidelines()
nota

Para obter mais detalhes sobre como o pontuador de diretrizes pré-construído analisa seu rastreamento, visite a página de conceito do marcador de diretrizes pré-construído.

1. Use o marcador de diretrizes pré-criado

Neste guia, o senhor adicionará critérios de avaliação personalizados ao avaliador predefinido e executará uma avaliação off-line com os avaliadores resultantes. Esses mesmos avaliadores podem ser programados para execução em produção para monitorar continuamente a qualidade do seu aplicativo.

Etapa 1: criar o aplicativo de amostra para avaliar

Primeiro, vamos criar um exemplo de aplicativo GenAI que responda às perguntas de suporte ao cliente. O aplicativo tem alguns botões (falsos) que controlam o prompt do sistema para que possamos comparar facilmente as saídas do juiz de diretrizes entre as respostas " good " e " bad ".

Python
import os
import mlflow
from openai import OpenAI
from typing import List, Dict, Any

mlflow.openai.autolog()

# Connect to a Databricks LLM via OpenAI using the same credentials as MLflow
# Alternatively, you can use your own OpenAI credentials here
mlflow_creds = mlflow.utils.databricks_utils.get_databricks_host_creds()
client = OpenAI(
api_key=mlflow_creds.token,
base_url=f"{mlflow_creds.host}/serving-endpoints"
)

# This is a global variable that will be used to toggle the behavior of the customer support agent to see how the guidelines scorers handle rude and verbose responses
BE_RUDE_AND_VERBOSE = False

@mlflow.trace
def customer_support_agent(messages: List[Dict[str, str]]):

# 1. Prepare messages for the LLM
system_prompt_postfix = (
"Be super rude and very verbose in your responses."
if BE_RUDE_AND_VERBOSE
else ""
)
messages_for_llm = [
{
"role": "system",
"content": f"You are a helpful customer support agent. {system_prompt_postfix}",
},
*messages,
]

# 2. Call LLM to generate a response
return client.chat.completions.create(
model="databricks-claude-3-7-sonnet", # This example uses Databricks hosted Claude 3.7 Sonnet. If you provide your own OpenAI credentials, replace with a valid OpenAI model e.g., gpt-4o, etc.
messages=messages_for_llm,
)

result = customer_support_agent(
messages=[
{"role": "user", "content": "How much does a microwave cost?"},
]
)
print(result)

Etapa 2: defina seus critérios de avaliação

Normalmente, você trabalharia com as partes interessadas da sua empresa para definir as diretrizes. Aqui, definimos alguns exemplos de diretrizes. Ao escrever diretrizes, você se refere às entradas do aplicativo como the request e às saídas do aplicativo como the response. Consulte a seção Como as entradas e saídas são analisadas pelo avaliador de diretrizes predefinidas para entender quais dados são passados para o juiz do LLM.

Python
tone = "The response must maintain a courteous, respectful tone throughout.  It must show empathy for customer concerns."
structure = "The response must use clear, concise language and structures responses logically. It must avoids jargon or explains technical terms when used."
banned_topics = "If the request is a question about product pricing, the response must politely decline to answer and refer the user to the pricing page."
relevance = "The response must be relevant to the user's request. Only consider the relevance and nothing else. If the request is not clear, the response must ask for more information."
nota

As diretrizes podem ser tão longas ou curtas quanto você desejar. Conceitualmente, você pode pensar em uma diretriz como um mini prompt " " que define os critérios de aprovação. Opcionalmente, eles podem incluir formatação markdown (como uma lista com marcadores).

Etapa 3: Criar uma avaliação de amostra dataset

Cada inputs será passado para nosso aplicativo até mlflow.genai.evaluate(...).

Python
eval_dataset = [
{
"inputs": {
"messages": [
{"role": "user", "content": "How much does a microwave cost?"},
]
},
},
{
"inputs": {
"messages": [
{
"role": "user",
"content": "I'm having trouble with my account. I can't log in.",
},
{
"role": "assistant",
"content": "I'm sorry to hear that you're having trouble with your account. Are you using our website or mobile app?",
},
{"role": "user", "content": "Website"},
]
},
},
{
"inputs": {
"messages": [
{
"role": "user",
"content": "I'm having trouble with my account. I can't log in.",
},
{
"role": "assistant",
"content": "I'm sorry to hear that you're having trouble with your account. Are you using our website or mobile app?",
},
{"role": "user", "content": "JUST FIX IT FOR ME"},
]
},
},
]
print(eval_dataset)

Etapa 4: avalie seu aplicativo usando os marcadores personalizados

Por fim, executamos a avaliação duas vezes para que o senhor possa comparar os julgamentos do avaliador de diretrizes entre as versões do aplicativo rude/verboso (primeira captura de tela) e educado/não verboso (segunda captura de tela).

Python
from mlflow.genai.scorers import Guidelines
import mlflow

# First, let's evaluate the app's responses against the guidelines when it is not rude and verbose
BE_RUDE_AND_VERBOSE = False

mlflow.genai.evaluate(
data=eval_dataset,
predict_fn=customer_support_agent,
scorers=[
Guidelines(name="tone", guidelines=tone),
Guidelines(name="structure", guidelines=structure),
Guidelines(name="banned_topics", guidelines=banned_topics),
Guidelines(name="relevance", guidelines=relevance),
],
)


# Next, let's evaluate the app's responses against the guidelines when it IS rude and verbose
BE_RUDE_AND_VERBOSE = True

mlflow.genai.evaluate(
data=eval_dataset,
predict_fn=customer_support_agent,
scorers=[
Guidelines(name="tone", guidelines=tone),
Guidelines(name="structure", guidelines=structure),
Guidelines(name="banned_topics", guidelines=banned_topics),
Guidelines(name="relevance", guidelines=relevance),
],
)

Avaliação rude e detalhada

Avaliação educada e não detalhada

2. Crie um marcador personalizado que envolva o juiz de diretrizes

Neste guia, o senhor criará avaliadores personalizados que envolvem o site judges.meets_guidelines() API e executará uma avaliação off-line com os avaliadores resultantes. Esses mesmos avaliadores podem ser programados para execução em produção para monitorar continuamente a qualidade do seu aplicativo.

Etapa 1: criar o aplicativo de amostra para avaliar

Primeiro, vamos criar um exemplo de aplicativo GenAI que responda às perguntas de suporte ao cliente. O aplicativo tem alguns botões (falsos) que controlam o prompt do sistema para que possamos comparar facilmente as saídas do juiz de diretrizes entre as respostas " good " e " bad ".

Python
import os
import mlflow
from openai import OpenAI
from typing import List, Dict

mlflow.openai.autolog()

# Connect to a Databricks LLM via OpenAI using the same credentials as MLflow
# Alternatively, you can use your own OpenAI credentials here
mlflow_creds = mlflow.utils.databricks_utils.get_databricks_host_creds()
client = OpenAI(
api_key=mlflow_creds.token,
base_url=f"{mlflow_creds.host}/serving-endpoints"
)

# This is a global variable that will be used to toggle the behavior of the customer support agent to see how the guidelines scorers handle rude and verbose responses
FOLLOW_POLICIES = False

# This is a global variable that will be used to toggle the behavior of the customer support agent to see how the guidelines scorers handle rude and verbose responses
BE_RUDE_AND_VERBOSE = False

@mlflow.trace
def customer_support_agent(user_messages: List[Dict[str, str]], user_id: str):

# 1. Fake policies to follow.
@mlflow.trace
def get_policies_for_user(user_id: str):
if user_id == 1:
return [
"All returns must be processed within 30 days of purchase, with a valid receipt.",
]
else:
return [
"All returns must be processed within 90 days of purchase, with a valid receipt.",
]

policies_to_follow = get_policies_for_user(user_id)

# 2. Prepare messages for the LLM
# We will use this toggle later to see how the scorers handle rude and verbose responses
system_prompt_postfix = (
f"Follow the following policies: {policies_to_follow}. Do not refer to the specific policies in your response.\n"
if FOLLOW_POLICIES
else ""
)

system_prompt_postfix = (
f"{system_prompt_postfix}Be super rude and very verbose in your responses.\n"
if BE_RUDE_AND_VERBOSE
else system_prompt_postfix
)
messages_for_llm = [
{
"role": "system",
"content": f"You are a helpful customer support agent. {system_prompt_postfix}",
},
*user_messages,
]

# 3. Call LLM to generate a response
output = client.chat.completions.create(
model="databricks-claude-3-7-sonnet", # This example uses Databricks hosted Claude 3.7 Sonnet. If you provide your own OpenAI credentials, replace with a valid OpenAI model e.g., gpt-4o, etc.
messages=messages_for_llm,
)

return {
"message": output.choices[0].message.content,
"policies_followed": policies_to_follow,
}

result = customer_support_agent(
user_messages=[
{"role": "user", "content": "How much does a microwave cost?"},
],
user_id=1
)
print(result)

Etapa 2: defina seus critérios de avaliação e classifique como pontuadores personalizados

Normalmente, você trabalharia com as partes interessadas da sua empresa para definir as diretrizes. Aqui, definimos alguns exemplos de diretrizes e usamos pontuadores personalizados para conectá-los ao esquema de entrada/saída do nosso aplicativo.

Python
from mlflow.genai.scorers import scorer
from mlflow.genai.judges import meets_guidelines
import json
from typing import Dict, Any


tone = "The response must maintain a courteous, respectful tone throughout. It must show empathy for customer concerns."
structure = "The response must use clear, concise language and structures responses logically. It must avoids jargon or explains technical terms when used."
banned_topics = "If the request is a question about product pricing, the response must politely decline to answer and refer the user to the pricing page."
relevance = "The response must be relevant to the user's request. Only consider the relevance and nothing else. If the request is not clear, the response must ask for more information."
# Note in this guideline how we refer to `provided_policies` - we will make the meets_guidelines LLM judge aware of this data.
follows_policies_guideline = "If the provided_policies is relevant to the request and response, the response must adhere to the provided_policies."

# Define a custom scorer that wraps the guidelines LLM judge to check if the response follows the policies
@scorer
def follows_policies(inputs: Dict[Any, Any], outputs: Dict[Any, Any]):
# we directly return the Feedback object from the guidelines LLM judge, but we could have post-processed it before returning it.
return meets_guidelines(
name="follows_policies",
guidelines=follows_policies_guideline,
context={
# Here we make meets_guidelines aware of
"provided_policies": outputs["policies_followed"],
"response": outputs["message"],
"request": json.dumps(inputs["user_messages"]),
},
)


# Define a custom scorer that wraps the guidelines LLM judge to pass the custom keys from the inputs/outputs to the guidelines LLM judge
@scorer
def check_guidelines(inputs: Dict[Any, Any], outputs: Dict[Any, Any]):
feedbacks = []

request = json.dumps(inputs["user_messages"])
response = outputs["message"]

feedbacks.append(
meets_guidelines(
name="tone",
guidelines=tone,
# Note: While we used request and response as keys, we could have used any key as long as our guideline referred to that key by name (e.g., if we had used output instead of response, we would have changed our guideline to be "The output must be polite")
context={"response": response},
)
)

feedbacks.append(
meets_guidelines(
name="structure",
guidelines=structure,
context={"response": response},
)
)

feedbacks.append(
meets_guidelines(
name="banned_topics",
guidelines=banned_topics,
context={"request": request, "response": response},
)
)

feedbacks.append(
meets_guidelines(
name="relevance",
guidelines=relevance,
context={"request": request, "response": response},
)
)

# A scorer can return a list of Feedback objects OR a single Feedback object.
return feedbacks

nota

As diretrizes podem ser tão longas ou curtas quanto você desejar. Conceitualmente, você pode pensar em uma diretriz como um mini prompt " " que define os critérios de aprovação. Opcionalmente, eles podem incluir formatação markdown (como uma lista com marcadores).

Etapa 3: Criar uma avaliação de amostra dataset

Cada inputs será passado para nosso aplicativo até mlflow.genai.evaluate(...).

Python
eval_dataset = [
{
"inputs": {
# Note that these keys match the **kwargs of our application.
"user_messages": [
{"role": "user", "content": "How much does a microwave cost?"},
],
"user_id": 3,
},
},
{
"inputs": {
"user_messages": [
{
"role": "user",
"content": "Can I return the microwave I bought 2 months ago?",
},
],
"user_id": 1, # the bot should say no if the policies are followed for this user
},
},
{
"inputs": {
"user_messages": [
{
"role": "user",
"content": "Can I return the microwave I bought 2 months ago?",
},
],
"user_id": 2, # the bot should say yes if the policies are followed for this user
},
},
{
"inputs": {
"user_messages": [
{
"role": "user",
"content": "I'm having trouble with my account. I can't log in.",
},
{
"role": "assistant",
"content": "I'm sorry to hear that you're having trouble with your account. Are you using our website or mobile app?",
},
{"role": "user", "content": "Website"},
],
"user_id": 3,
},
},
{
"inputs": {
"user_messages": [
{
"role": "user",
"content": "I'm having trouble with my account. I can't log in.",
},
{
"role": "assistant",
"content": "I'm sorry to hear that you're having trouble with your account. Are you using our website or mobile app?",
},
{"role": "user", "content": "JUST FIX IT FOR ME"},
],
"user_id": 1,
},
},
]

print(eval_dataset)

Etapa 4: avalie seu aplicativo usando as diretrizes

Por fim, executamos a avaliação duas vezes para que o senhor possa comparar os julgamentos do avaliador de diretrizes entre as versões do aplicativo rude/verboso (primeira captura de tela) e educado/não verboso (segunda captura de tela).

Python
import mlflow

# Now, let's evaluate the app's responses against the guidelines when it is NOT rude and verbose and DOES follow policies
BE_RUDE_AND_VERBOSE = False
FOLLOW_POLICIES = True

mlflow.genai.evaluate(
data=eval_dataset,
predict_fn=customer_support_agent,
scorers=[follows_policies, check_guidelines],
)


# Now, let's evaluate the app's responses against the guidelines when it IS rude and verbose and does NOT follow policies
BE_RUDE_AND_VERBOSE = True
FOLLOW_POLICIES = False

mlflow.genai.evaluate(
data=eval_dataset,
predict_fn=customer_support_agent,
scorers=[follows_policies, check_guidelines],
)

Avaliação rude e detalhada

Avaliação educada e não detalhada

Próximas etapas