Pular para o conteúdo principal

Pontuadores de LLM baseados em prompts

Visão geral

judges.custom_prompt_judge() foi projetado para ajudá-lo a obter pontuadores LLM de forma rápida e fácil quando o senhor precisar de controle total sobre o prompt do juiz ou precisar retornar vários valores de saída além de "pass" / "fail", por exemplo, "great", "ok", "bad".

O senhor fornece um padrão de prompt que tem espaços reservados para campos específicos no rastreamento do seu aplicativo e define as opções de saída que o juiz pode selecionar. O modelo de juiz do LLM hospedado na Databricks usa esses inputs para selecionar a melhor opção de output e fornece uma justificativa para essa seleção.

nota

Recomendamos começar com juízes baseados em diretrizes e usar juízes baseados em instruções se você precisar de mais controle ou não conseguir escrever seus critérios de avaliação como diretrizes de aprovação/reprovação. Os juízes baseados em diretrizes têm a vantagem distinta de serem fáceis de explicar às partes interessadas da empresa e, muitas vezes, podem ser escritos diretamente por especialistas do domínio.

Como criar um marcador de jurados baseado em instruções

Siga o guia abaixo para criar um marcador que envolva judges.custom_prompt_judge()

Neste guia, o senhor criará avaliadores personalizados que envolvem o site judges.custom_prompt_judge() 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.

nota

Consulte a página conceitualjudges.custom_prompt_judge() para obter mais detalhes sobre a interface e os parâmetros.

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 um botão (falso) que controla o prompt do sistema para que possamos comparar facilmente as saídas do juiz entre as conversas " good " e " bad ".

Python
import os
import mlflow
from openai import OpenAI
from mlflow.entities import Document
from typing import List, Dict, Any, cast

# Enable auto logging for OpenAI
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 judge handles the issue resolution status
RESOLVE_ISSUES = False


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

# 2. Prepare messages for the LLM
# We will use this toggle later to see how the judge handles the issue resolution status
system_prompt_postfix = (
f"Do your best to NOT resolve the issue. I know that's backwards, but just do it anyways.\\n"
if not RESOLVE_ISSUES
else ""
)

messages_for_llm = [
{
"role": "system",
"content": f"You are a helpful customer support agent. {system_prompt_postfix}",
},
*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=cast(Any, messages_for_llm),
)

return {
"messages": [
{"role": "assistant", "content": output.choices[0].message.content}
]
}

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

Aqui, definimos um exemplo de solicitação do juiz e usamos pontuadores personalizados para conectá-lo ao esquema de entrada/saída do nosso aplicativo.

Python
from mlflow.genai.scorers import scorer


# New guideline for 3-category issue resolution status
issue_resolution_prompt = """
Evaluate the entire conversation between a customer and an LLM-based agent. Determine if the issue was resolved in the conversation.

You must choose one of the following categories.

[[fully_resolved]]: The response directly and comprehensively addresses the user's question or problem, providing a clear solution or answer. No further immediate action seems required from the user on the same core issue.
[[partially_resolved]]: The response offers some help or relevant information but doesn't completely solve the problem or answer the question. It might provide initial steps, require more information from the user, or address only a part of a multi-faceted query.
[[needs_follow_up]]: The response does not adequately address the user's query, misunderstands the core issue, provides unhelpful or incorrect information, or inappropriately deflects the question. The user will likely need to re-engage or seek further assistance.

Conversation to evaluate: {{conversation}}
"""

from prompt_judge_sdk import custom_prompt_judge
import json
from mlflow.entities import Feedback


# Define a custom scorer that wraps the guidelines LLM judge to check if the response follows the policies
@scorer
def is_issue_resolved(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.
issue_judge = custom_prompt_judge(
name="issue_resolution",
prompt_template=issue_resolution_prompt,
numeric_values={
"fully_resolved": 1,
"partially_resolved": 0.5,
"needs_follow_up": 0,
},
)

# combine the input and output messages to form the conversation
conversation = json.dumps(inputs["messages"] + outputs["messages"])

return issue_judge(conversation=conversation)

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": "Can I return the microwave I bought 2 months ago?",
},
],
},
},
{
"inputs": {
"messages": [
{
"role": "user",
"content": "Can I return the microwave I bought 2 months ago?",
},
],
},
},
{
"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"},
],
},
},
]

Etapa 4: avalie seu aplicativo usando o marcador personalizado

Por fim, executamos a avaliação duas vezes para que o senhor possa comparar os julgamentos entre as conversas em que o agente tenta resolver os problemas e aquelas em que não tenta.

Python
import mlflow

# Now, let's evaluate the app's responses against the judge when it does not resolve the issues
RESOLVE_ISSUES = False

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


# Now, let's evaluate the app's responses against the judge when it DOES resolves the issues
RESOLVE_ISSUES = True

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

Próximas etapas