Aller au contenu principal

Didacticiel sur l'optimisation des prompts

Cet exemple de tutoriel optimise un simple prompt classer cette query en utilisant l'optimisation des prompts MLflow avec GEPA et GPT-OSS 20B pour les tâches de classification.

Installer les dépendances

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

Assurez-vous d'avoir accès aux APIs de modèles de fondation Databricks pour l'exécuter avec succès.

Python
import mlflow
import openai
from mlflow.genai.optimize import GepaPromptOptimizer
from mlflow.genai.scorers import Correctness
from databricks_openai import DatabricksOpenAI

# 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 = DatabricksOpenAI()

# 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



Tester votre fonction

Observez avec quelle précision le modèle peut classer l’entrée avec une invite de base. Bien que précis, il ne correspond à aucune tâche ou à aucun cas d'usage que vous recherchez.

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'])

Optimiser par rapport aux données

Fournissez des données avec les réponses et les faits attendus pour aider à optimiser le comportement et la sortie du modèle d'une manière qui correspond à vos cas d'utilisation.

Dans ce cas, vous voulez que le modèle génère un mot parmi un choix de cinq mots. Il ne doit générer que ce mot sans autre explication.

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

Vérifier votre prompt

Ouvrez le Link vers votre expérience MLflow et suivez les étapes ci-dessous pour que les invites apparaissent dans votre expérience :

  1. Assurez-vous que votre type d'expérimentation est défini sur les applications et agents GenAI.
  2. Accédez à l'onglet tab
  3. Cliquez sur sélectionner un schéma en haut à droite et saisissez le même schéma que celui que vous avez défini ci-dessus pour voir votre invite.

Charger la nouvelle invite et tester à nouveau

Voyez à quoi ressemble l'invite et chargez-la dans votre fonction de prédiction pour voir comment le modèle se comporte différemment.

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'])

Exemple de Notebook

Le texte suivant est un notebook exécutable qui optimise les prompts à l'aide de l'optimisation de prompt MLflow GenAI avec GEPA et démontre des tâches de classification avec GPT-OSS 20B.

Optimisation des prompts à l'aide de GEPA et GPT-OSS 20B