La creazione dei prompt per i modelli LLM, come ChatGPT, può considerasi una nuova arte. Dalla strutturazione delle domande all'utilizzo del contesto, è possibile migliorare l'esperienza di conversazione ed estrarre il massimo valore dalle interazioni con gli LLM. Mediante esempi pratici vedremo come strutturare al meglio i prompt per generare conversazioni coinvolgenti e significative con l'AI in base al compito prefissato.

Share

Reading time: 7 minutes

Nell’articolo Ingegneria dei prompt, abbiamo introdotto la figura dell’ingegnere dei prompt. Questa figura è responsabile di studiare i modelli linguistici di grandi dimensioni (LLM) al fine di definire la struttura migliore dei dati in input per ottenere i risultati migliori. Come abbiamo visto, esistono alcuni suggerimenti di come strutturare al meglio le richieste, anche se tuttavia solo con la pratica e l’esperienza si otterranno i risultati attesi. Per favorire l’utilizzo adeguato dei LLM, analizzeremo di seguito alcuni prompt relativi a dei casi d’uso reali introducendo alcuni concetti chiave lungo il percorso. Spesso, infatti, il modo migliore per imparare i concetti è attraverso gli esempi. Partiamo allora!

Generazioni di riassunti

Uno dei compiti standard nella generazione del linguaggio naturale è la generazione di riassunti, detta anche summarizzazione. Nel tempo sono stati sviluppati diversi algoritmi per generare un riassunto partendo da una collezione di testi. L’avvento dei LLM ha superato di gran lunga i risultati ottenuti fin ad allora.

Il riassunto può includere molti aspetti e domini diversi. In effetti, una delle applicazioni più promettenti dei modelli linguistici è la capacità di riassumere articoli e concetti in sintesi rapide e di facile lettura. Proviamo a svolgere un compito di riassunto di base utilizzando i prompt.

Supponiamo che siamo interessati a conoscere gli antibiotici, potremmo provare un prompt come questo:

				
					Explain the antibiotics
R:

				
			

Output:

				
					Antibiotics are medicines used to treat bacterial infections in the body. They work by either killing the bacteria or stopping their growth. It's important to note that antibiotics don't work against viral infections like the common cold or flu. Using antibiotics correctly and only when necessary helps prevent the development of antibiotic resistance, which can make some bacteria harder to treat in the future.

				
			

La risposta ottenuta è inerente alla domanda. Ma a cosa serve “R:” al termine del prompt? Questo è un formato di prompt esplicito che viene utilizzato nelle risposte alle domande. Qui lo abbiamo usato per dire al modello che c’è un’ulteriore attesa. In questo esempio, non è evidente in che modo sia utile rispetto a non usarlo, ma considerate che potrebbe influire sul risultato in base al LLM usato. Supponiamo che queste informazioni siano troppe e che si voglia riassumerle ulteriormente. In effetti, possiamo istruire il modello a riassumere in una frase come questa:

				
					Antibiotics are a type of drug used to treat bacterial infections. They work by killing bacteria or preventing them from reproducing, allowing the body's immune system to fight the infection. Antibiotics are usually taken orally in the form of pills, capsules or liquid solutions, or sometimes given intravenously. They are not effective against viral infections, and their inappropriate use can lead to antibiotic resistance.
Explain the above in one sentence:


				
			

Output:

				
					Antibiotics are drugs that combat bacterial infections by either destroying the bacteria or inhibiting their reproduction, enabling the body's immune system to tackle the infection, typically administered orally or intravenously, but they are ineffective against viral infections and misuse can lead to antibiotic resistance.


				
			

Senza prestare troppa attenzione all’accuratezza dell’output di cui sopra, il modello ha cercato di riassumere il paragrafo in una frase.

Estrazione di informazioni

Sebbene i modelli linguistici siano addestrati per eseguire la generazione del linguaggio naturale e i compiti correlati, sono anche in grado di eseguire tecniche di elaborazione del linguaggio naturale (NLP) come ad esempio la classificazione e il named entity recognition.

Possiamo, ad esempio, chiedere di estrarre l’oggetto descritto in un paragrafo!

				
					Author contribution statements and acknowledgements in research papers should clearly and specifically indicate whether, and to what extent, the authors used AI technologies such as ChatGPT in the preparation of the manuscript and analysis. They should also indicate which LLMs were used. This will enable editors and reviewers to examine manuscripts more closely for potential biases, inaccuracies, and improper crediting of sources. Similarly, scientific journals should be transparent about the use of LLMs, such as in the selection of submitted manuscripts.
Cite the large language model-based product mentioned in the previous paragraph:



				
			

Output:

				
					The large language model-based product mentioned in the previous paragraph is "ChatGPT."



				
			

Ci sono molti modi per migliorare i risultati che abbiamo appena visto, ma questi esempi ci mostrano già le potenzialità dei LLM.

A questo punto dovrebbe essere ovvio che si può chiedere al modello di eseguire compiti diversi semplicemente dandogli istruzioni su cosa fare. Si tratta di una capacità potente che gli sviluppatori di prodotti di intelligenza artificiale stanno già utilizzando per creare prodotti ed esperienze di grande impatto.

Rispondere alle domande

Uno dei modi migliori per far sì che il modello risponda a risposte specifiche è migliorare il formato del prompt. Un prompt può combinare istruzioni, contesto, indicatori di input e output per ottenere risultati migliori (vedi articolo XXX). Anche se questi componenti non sono obbligatori, è buona prassi includerli, poiché quanto più specifiche sono le istruzioni, tanto migliori saranno i risultati. Di seguito è riportato un esempio di come potrebbe apparire un prompt più strutturato.

				
					Answer the question based on the underlying context. Answer briefly and concisely. Answer "Uncertain about answer" if you are unsure of the answer.
Context: Teplizumab has its roots in a New Jersey pharmaceutical company, Ortho Pharmaceutical. Here scientists generated an early version of the antibody, called OKT3. Originally obtained from mice, the molecule was able to bind to the surface of T cells and limit their killing potential. In 1986 it was approved to help prevent organ rejection after kidney transplantation, making it the first therapeutic antibody approved for human use.
Question: From what was OKT3 originally derived?
Answer:




				
			

Output:

				
					OKT3 was originally derived from mice.




				
			

Classificazione del testo

Finora abbiamo usato istruzioni semplici per eseguire un compito. Come ingegneri del prompt, dovrete migliorare nel fornire istruzioni più precise. Ma non è tutto! Scoprirete anche che, per i casi d’uso più difficili, fornire solo istruzioni non sarà sufficiente. Bisogna, infatti, pensare di più al contesto e ai diversi elementi che si possono usare in un prompt. Altri elementi che si possono fornire sono i dati di input o esempi.

Vediamo come possiamo utilizzare un prompt per classificare un testo, senza necessariamente costruire un dataset ad hoc e un modello per farlo.

				
					Classify the text into neutral, negative or positive. 
Text: I think the food was good. 
Sentiment:





				
			

Output:

				
					Sentiment: Positive




				
			

Abbiamo dato l’istruzione di classificare il testo e il modello ha risposto con “Sentiment: Positive”, che è corretto. Non c’è nulla di male in questo, ma diciamo che ciò di cui abbiamo bisogno è che il modello fornisca l’etichetta nel formato esatto che vogliamo. Quindi, invece della frase intera, vogliamo che restituisca solamente una delle etichette definite all’inizio. Come possiamo ottenere questo risultato? Ci sono diversi modi per farlo. Poiché ci interessa la specificità, più informazioni forniamo al prompt migliori saranno i risultati. Possiamo provare a fornire degli esempi per specificare il comportamento corretto. Proviamo di nuovo:

				
					Classify the text into neutral, negative or positive. 
Text: I think the vacation is going well.
Sentiment: neutral
Text: I think the food was good. 
Sentiment:



				
			

Output:

				
					positive



				
			

Attenzione

Iniziate una nuova chat ogni volta se no la memoria delle risposte precedenti potrebbe influenzare il risultato ottenuto!

Conversazione

Forse una delle cose più interessanti che si possono ottenere con l’ingegneria dei prompt è istruire il sistema LLM su come comportarsi, sulle sue intenzioni e sulla sua identità. Questo è particolarmente utile quando si costruiscono sistemi conversazionali come i chatbot del servizio clienti.

Per esempio, creiamo un sistema conversazionale in grado di generare risposte più tecniche e scientifiche alle domande. Notate come gli stiamo dicendo esplicitamente come comportarsi attraverso le istruzioni. Questo viene a volte definito “prompting di ruolo”.

				
					The following is a conversation with an artificial intelligence (AI) research assistant. The assistant's tone is technical and scientific.
Person: Hello, who are you?
AI: Hello! I am an AI research assistant. How can I help you today?
Person: Can you tell me about the creation of black holes?
AI:



				
			

Output:

				
					Certainly. Black holes are formed through a process known as gravitational collapse. This occurs when a massive star undergoes a catastrophic event, such as a supernova explosion, at the end of its life cycle. 

During a supernova, the outer layers of the star are expelled into space, while the core collapses under its own gravitational pull. If the core's mass is above a critical threshold (approximately 2.5 to 3 solar masses), it will continue to collapse indefinitely, forming a region of infinite density and curvature known as a singularity at its center. This singularity is surrounded by an event horizon, which is the boundary beyond which no information or matter can escape, including light.

The size of the event horizon is determined solely by the mass of the black hole and is proportional to it. For instance, a black hole with ten times the mass of our Sun will have an event horizon roughly ten times larger in diameter.

It's important to note that black holes can also form from other processes, such as the collapse of massive clouds of gas without the need for a precursor star. These are known as primordial black holes.

Is there a specific aspect of black holes you would like to explore further?


				
			

Il nostro assistente di ricerca AI sembra un po’ troppo tecnico, vero? Ok, cambiamo questo comportamento e istruiamo il sistema a dare risposte più accessibili.

				
					The following is a conversation with an AI research assistant. The assistant's answers should be easy for even elementary school students to understand.
Person: Hello, who are you?
AI: Hello! I'm an AI research assistant. How can I help you today?
Person: Can you tell me about the creation of black holes?
AI:
				
			

Output:

				
					Sure! Black holes are like really special objects in space. They happen when a big star runs out of energy and collapses. This makes a super strong force that sucks in everything around it, even light! That's why it's called a "black" hole. It's like a place where things disappear. They're really interesting, but we can't see them directly because they don't give off light. We learn about them by studying how they affect things around them. Isn't space cool? 😊
				
			

Il risultato è notevolmente migliorato. È stata usata un emoji per rendere l’assistente più “amichevole”. Ottimo risultato! Ovviamente questo è un punto di partenza e con la pratica possiamo raggiungere risultati sempre più dettagliati e in linea con il contesto applicativo che abbiamo in mente.

Generazione di codice

Un’applicazione in cui gli LLM sono molto efficaci è la generazione di codice. È possibile eseguire un gran numero di operazioni di generazione di codice con suggerimenti intelligenti. Vediamo di seguito alcuni esempi.

Per prima cosa, proviamo un semplice programma che saluta l’utente.

				
					/*
Ask the user his name and to "Hello."
*/
				
			

Output:

				
					Certainly! Here is a simple code snippet in C++ that asks the user for their name and then greets them:

```cpp
#include <iostream>
#include <string>

int main() {
    std::string name;

    std::cout << "What is your name? ";
    std::getline(std::cin, name);

    std::cout << "Hello, " << name << "!" << std::endl;

    return 0;
}
```

This program prompts the user to enter their name, reads it, and then prints out a greeting using their name.

				
			

Si può notare che non è stato necessario specificare la lingua da utilizzare. Il sistema ha automaticamente deciso quale linguaggio utilizzare. In alcuni casi potrebbe chiederlo per essere più preciso nella risposta.

Cambiamo un po’ livello. Voglio mostrarvi quanto possano essere potenti gli LLM con un po’ più di impegno nella progettazione dei prompt.

				
					"""
Table departments, columns = [DepartmentId, DepartmentName]
Student table, columns = [DepartmentId, StudentId, StudentName]
Create a MySQL query for all students in the Computer Science department.
"""
				
			

Output:

				
					To retrieve all students in the Computer Science department from the given tables, you can use a simple SQL query with a `JOIN` statement. Assuming that the DepartmentId for Computer Science is known (let's assume it's 1 for this example), the query would look like this:

```sql
SELECT Student.StudentId, Student.StudentName
FROM Student
JOIN Departments ON Student.DepartmentId = Departments.DepartmentId
WHERE Departments.DepartmentName = 'Computer Science';
```

This query joins the `Student` table with the `Departments` table based on the `DepartmentId` column. Then, it selects the `StudentId` and `StudentName` columns from the `Student` table for rows where the `DepartmentName` in the `Departments` table is 'Computer Science'.

				
			

È davvero impressionante. In questo caso, abbiamo fornito dati sullo schema del database e gli abbiamo chiesto di generare una query MySQL valida. Oltre al codice SQL abbiamo anche avuto una spiegazione di come è strutturata la query.

Ragionamento

Forse uno dei compiti più difficili per un LLM oggi è quello che richiede una qualche forma di ragionamento. Il ragionamento è una delle aree che mi entusiasmano di più, per il tipo di applicazioni complesse che possono emergere dai LLM.

Ci sono stati alcuni miglioramenti nei compiti che richiedono capacità matematiche. Detto questo, è importante notare che gli attuali LLM faticano a svolgere compiti di ragionamento, quindi questo richiede tecniche di prompt engineering ancora più avanzate. Vediamo alcuni esempi di base per mostrare le capacità aritmetiche.

				
					What is 9,000 * 9,000?
				
			

Output:

				
					The product of 9,000 multiplied by 9,000 is 81,000,000.
				
			

Proviamo a fare qualcosa di più difficile.

				
					The sum of the odd numbers in this group generates an even number: 15, 32, 5, 13, 82, 7, 1. 
R:

				
			

Output:

				
					Let's find the sum of the odd numbers in the group:

Odd numbers in the group: 15, 5, 13, 7, 1

Sum of odd numbers = 15 + 5 + 13 + 7 + 1 = 41

Since 41 is an odd number, the statement "The sum of the odd numbers in this group generates an even number" is not true for this particular group of numbers.

				
			

Le capacità di comprensione sono veramente notevoli in quanto non ha dato solo la risposta ma anche il procedimento per raggiungerla.

More To Explore

Intelligenza artificiale

Gradio: applicazioni web in python per AI [parte2]

Gradio è una libraria python che ci permette di creare applicazioni web in modo veloce e intuitivo per i nostri modelli di machine learning e AI. Le nostre applicazioni richiedono sempre un’interazione con l’utente e una personalizzazione del layout. Scopriamo, mediante degli esempi, come migliorare le nostre applicazioni.

Intelligenza artificiale

Gradio: applicazioni web in python per AI [parte1]

Scrivere applicazioni web per i nostri modelli di machine learning e/o di intelligenza artificiale può richiedere molto tempo e competenze che non sono in nostro possesso. Per snellire e velocizzare questo compito ci viene in aiuto Gradio, una libreria Python pensata per creare applicazioni web con poche righe di codice. Scopriamo le sue funzionalità base con alcuni esempi.

Lascia un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *

Design with MongoDB

Design with MongoDB!!!

Buy the new book that will help you to use MongoDB correctly for your applications. Available now on Amazon!