Pular para o conteúdo principal

tutorialde otimização de prompts

Este exemplo tutorial otimiza uma consulta simples de classificação usando a Otimização de Consultas MLflow com GEPA e GPT-OSS 20B para a tarefa de classificação.

Instalar dependências

Python
%pip install --upgrade mlflow databricks-sdk dspy openai
dbutils.library.restartPython()

Certifique-se de ter acesso às APIs do Databricks Foundation Model para executar isso com sucesso.

Python
import mlflow
import openai
from mlflow.genai.optimize import GepaPromptOptimizer
from mlflow.genai.scorers import Correctness
from databricks.sdk import WorkspaceClient

w = WorkspaceClient()

# Change the catalog and schema to your catalog and schema
catalog = ""
schema = ""
prompt_registry_name = "qa"
prompt_location = f"{catalog}.{schema}.{prompt_registry_name}"

openai_client = w.serving_endpoints.get_open_ai_client()

# Register initial prompt
prompt = mlflow.genai.register_prompt(
name=prompt_location,
template="classify this: {{query}}",
)


# Define your prediction function
def predict_fn(query: str) -> str:
prompt = mlflow.genai.load_prompt(f"prompts:/{prompt_location}/1")
completion = openai_client.chat.completions.create(
model="databricks-gpt-oss-20b",
# load prompt template using PromptVersion.format()
messages=[{"role": "user", "content": prompt.format(question=query)}],
)
return completion.choices[0].message.content



Teste sua função

Observe a precisão com que o modelo consegue classificar a entrada com um enunciado bastante básico. Embora preciso, não está alinhado a nenhuma tarefa ou caso de uso que você esteja procurando.

Python
from IPython.display import Markdown

output = predict_fn("The emergence of HIV as a chronic condition means that people living with HIV are required to take more responsibility for the self-management of their condition , including making physical , emotional and social adjustments.")

Markdown(output[1]['text'])

Otimizar com base em dados

Forneça dados com respostas esperadas e fatos para ajudar a otimizar o comportamento e a saída do modelo de uma forma que se adeque aos seus casos de uso.

Nesse caso, você quer que o modelo produza uma palavra a partir de uma seleção de cinco palavras. Deveria exibir apenas essa palavra, sem qualquer explicação adicional.

Python
# Training data with inputs and expected outputs
dataset = [
{
"inputs": {"query": "The emergence of HIV as a chronic condition means that people living with HIV are required to take more responsibility for the self-management of their condition , including making physical , emotional and social adjustments."},
"outputs": {"response": "BACKGROUND"},
"expectations": {"expected_facts": ["Classification label must be 'CONCLUSIONS', 'RESULTS', 'METHODS', 'OBJECTIVE', 'BACKGROUND'"]}
},
{
"inputs": {"query": "This paper describes the design and evaluation of Positive Outlook , an online program aiming to enhance the self-management skills of gay men living with HIV ."},
"outputs": {"response": "BACKGROUND"},
"expectations": {"expected_facts": ["Classification label must be 'CONCLUSIONS', 'RESULTS', 'METHODS', 'OBJECTIVE', 'BACKGROUND'"]}
},
{
"inputs": {"query": "This study is designed as a randomised controlled trial in which men living with HIV in Australia will be assigned to either an intervention group or usual care control group ."},
"outputs": {"response": "METHODS"},
"expectations": {"expected_facts": ["Classification label must be 'CONCLUSIONS', 'RESULTS', 'METHODS', 'OBJECTIVE', 'BACKGROUND'"]}
},
{
"inputs": {"query": "The intervention group will participate in the online group program ` Positive Outlook ' ."},
"outputs": {"response": "METHODS"},
"expectations": {"expected_facts": ["Classification label must be 'CONCLUSIONS', 'RESULTS', 'METHODS', 'OBJECTIVE', 'BACKGROUND'"]}
},
{
"inputs": {"query": "The program is based on self-efficacy theory and uses a self-management approach to enhance skills , confidence and abilities to manage the psychosocial issues associated with HIV in daily life ."},
"outputs": {"response": "METHODS"},
"expectations": {"expected_facts": ["Classification label must be 'CONCLUSIONS', 'RESULTS', 'METHODS', 'OBJECTIVE', 'BACKGROUND'"]}
},
{
"inputs": {"query": "Participants will access the program for a minimum of 90 minutes per week over seven weeks ."},
"outputs": {"response": "METHODS"},
"expectations": {"expected_facts": ["Classification label must be 'CONCLUSIONS', 'RESULTS', 'METHODS', 'OBJECTIVE', 'BACKGROUND'"]}
}
]

# Optimize the prompt
result = mlflow.genai.optimize_prompts(
predict_fn=predict_fn,
train_data=dataset,
prompt_uris=[prompt.uri],
optimizer=GepaPromptOptimizer(reflection_model="databricks:/databricks-claude-sonnet-4-5"),
scorers=[Correctness(model="databricks:/databricks-gpt-5")],
)

# Use the optimized prompt
optimized_prompt = result.optimized_prompts[0]
print(f"Optimized template: {optimized_prompt.template}")

Analise suas instruções.

Abra o link para o seu experimento MLflow e siga os passos abaixo para que os prompts apareçam no seu experimento:

  1. Certifique-se de que o tipo de experimento esteja definido como "Aplicativos e agentes GenAI".
  2. Navegue até a tabde prompts.
  3. Clique em "Selecionar um esquema" no canto superior direito e insira o mesmo esquema que você definiu acima para ver o seu prompt.

Carregue o novo prompt e teste novamente.

Veja como é o prompt e carregue-o na sua função de previsão para observar as diferenças de desempenho do modelo.

Python
from IPython.display import Markdown
prompt = mlflow.genai.load_prompt(f"prompts:/{prompt_location}/34")

Markdown(prompt.template)
Python
from IPython.display import Markdown

def predict_fn(query: str) -> str:
prompt = mlflow.genai.load_prompt(f"prompts:/{prompt_location}/34")
completion = openai_client.chat.completions.create(
model="databricks-gpt-oss-20b",
# load prompt template using PromptVersion.format()
messages=[{"role": "user", "content": prompt.format(query=query)}],
)
return completion.choices[0].message.content

output = predict_fn("The emergence of HIV as a chronic condition means that people living with HIV are required to take more responsibility for the self-management of their condition , including making physical , emotional and social adjustments.")

Markdown(output[1]['text'])

Exemplo de caderno

Segue abaixo um Notebook executável que otimiza prompts usando MLflow GenAI Prompt Optimization com GEPA e demonstra uma tarefa de classificação com o GPT-OSS 20B.

Otimização imediata usando GEPA e GPT-OSS 20B

Open notebook in new tab