Linee guida generali per gli utenti degli LLM di Amazon Bedrock - Amazon Bedrock

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

Linee guida generali per gli utenti degli LLM di Amazon Bedrock

Progettazione di un prompt

La progettazione di un prompt appropriato è un passaggio importante verso la creazione di un'applicazione di successo utilizzando i modelli Amazon Bedrock. La figura seguente mostra una progettazione generica dei prompt per il riassunto della recensione di un ristorante, nonché alcune importanti scelte di progettazione dei prompt che i clienti devono prendere in considerazione. Gli LLM generano risposte indesiderate se le istruzioni fornite o il formato del prompt non sono coerenti, chiari e concisi.

Esempio di creazione corretta di un prompt con commenti descrittivi.

(Fonte: Prompt scritto da AWS)

Utilizzo dei parametri di inferenza

Gli LLM su Amazon Bedrock dispongono tutti di diversi parametri di inferenza che possono essere impostati per controllare la risposta dei modelli. Di seguito è riportato un elenco di tutti i parametri di inferenza più comuni disponibili negli LLM di Amazon Bedrock con le relative modalità di utilizzo.

La temperatura è un valore compreso tra 0 e 1 e regola la creatività delle risposte degli LLM. Usa una temperatura più bassa se desideri risposte più deterministiche oppure una temperatura più alta se vuoi avere risposte più creative o diverse per lo stesso prompt dagli LLM su Amazon Bedrock. Per tutti gli esempi in queste linee guida per i prompt, abbiamo impostato temperature = 0.

La lunghezza massima di generazione e il numero massimo di nuovi token limitano il numero di token generati dall'LLM per qualsiasi prompt. È utile specificare questo numero poiché alcune attività, come la classificazione del sentiment, non richiedono una risposta lunga.

Top-p controlla le scelte dei token, in base alla probabilità delle scelte potenziali. Se Top-p viene impostato al di sotto di 1,0, il modello considera le opzioni più probabili e ignora quelle meno probabili. Si otterranno costi completamenti più stabili e ripetitivi.

Token finale e sequenza finale specificano il token utilizzato dall'LLM per indicare la fine dell'output. Gli LLM smettono di generare nuovi token dopo aver incontrato il token finale. Di solito non deve essere impostato dagli utenti.

Esistono anche parametri di inferenza specifici del modello. AnthropicClaudei modelli hanno un parametro di inferenza Top-K aggiuntivo e i modelli AI21 Labs Jurassic sono dotati di una serie di parametri di inferenza tra cui penalità di presenza, penalità di conteggio, penalità di frequenza e penalità speciale con token. Per ulteriori informazioni, consulta la rispettiva documentazione.

Linee guida dettagliate

Fornisci istruzioni semplici, chiare e complete

Gli LLM su Amazon Bedrock funzionano al meglio con istruzioni semplici e dirette. Descrivi chiaramente le aspettative dell'attività e riduci l'ambiguità, se possibile, per fare in modo che il modello possa interpretare chiaramente il prompt.

Prendiamo come esempio un problema di classificazione in cui l'utente desidera una risposta tra una serie di scelte possibili. L'esempio "giusto" riportato di seguito mostra l'output che l'utente desidera in questo caso. Nell'esempio "sbagliato", le scelte non sono denominate esplicitamente come categorie tra cui il modello può scegliere. Il modello interpreta l'input in modo leggermente diverso senza scelte e produce un riepilogo del testo in formato più libero rispetto all'esempio giusto.

Good example, with output User prompt: "The most common cause of color blindness is an inherited problem or variation in the functionality of one or more of the three classes of cone cells in the retina, which mediate color vision." What is the above text about? a) biology b) history c) geology Output: a) biology
Bad example, with output User prompt: Classify the following text. "The most common cause of color blindness is an inherited problem or variation in the functionality of one or more of the three classes of cone cells in the retina, which mediate color vision."
Output: The topic of the text is the causes of colorblindness.

(Fonte del messaggio: Wikipedia sul daltonismo, modello utilizzato: da Text G1 - Express) Titan

La domanda o l'istruzione devono essere inserite alla fine del prompt per ottenere i risultati migliori

L'inclusione della descrizione dell'attività, dell'istruzione o della domanda alla fine aiuta il modello a determinare le informazioni che deve trovare. Nel caso della classificazione, anche le scelte relative alla risposta dovrebbero essere incluse alla fine.

Nel seguente esempio di domanda-risposta aperta, l'utente ha una domanda specifica sul testo. La domanda dovrebbe trovarsi alla fine del prompt, in modo che il modello possa concentrarsi sull'attività.

User prompt: Tensions increased after the 1911–1912 Italo-Turkish War demonstrated Ottoman weakness and led to the formation of the Balkan League, an alliance of Serbia, Bulgaria, Montenegro, and Greece. The League quickly overran most of the Ottomans' territory in the Balkans during the 1912–1913 First Balkan War, much to the surprise of outside observers. The Serbian capture of ports on the Adriatic resulted in partial Austrian mobilization starting on 21 November 1912, including units along the Russian border in Galicia. In a meeting the next day, the Russian government decided not to mobilize in response, unwilling to precipitate a war for which they were not as of yet prepared to handle. Which country captured ports?
Output: Serbia

(Fonte del messaggio: Wikipedia sulla prima guerra mondiale, modello utilizzato: Amazon Titan Text)

Usa caratteri separatori per le chiamate API

I caratteri separatori come \n possono influire in modo significativo sulle prestazioni degli LLM. Per Anthropic Claude i modelli, è necessario includere le nuove righe durante la formattazione delle chiamate API per ottenere le risposte desiderate. La formattazione dovrebbe sempre seguire questa struttura: \n\nHuman: {{Query Content}}\n\nAssistant:. Per Titan i modelli, l'aggiunta \n alla fine di un prompt aiuta a migliorare le prestazioni del modello. Per le attività di classificazione o le domande con opzioni di risposta, puoi anche separare le opzioni di risposta in base \n ai Titan modelli. Per ulteriori informazioni sull'uso dei separatori, consulta il documento del provider dei modelli corrispondente. L'esempio seguente è un modello per un'attività di classificazione.

Prompt template: """{{Text}} {{Question}} {{Choice 1}} {{Choice 2}} {{Choice 3}}"""

L'esempio seguente mostra come la presenza di caratteri di nuova riga tra le scelte e alla fine di un prompt contribuisca a Titan produrre la risposta desiderata.

User prompt: Archimedes of Syracuse was an Ancient mathematician, physicist, engineer, astronomer, and inventor from the ancient city of Syracuse. Although few details of his life are known, he is regarded as one of the leading scientists in classical antiquity. What was Archimedes? Choose one of the options below. a) astronomer b) farmer c) sailor
Output: a) astronomer

(Fonte del messaggio: Wikipedia su Archimede, modello utilizzato: Amazon Text) Titan

Indicatori di output

Aggiungi i dettagli sui vincoli che vuoi applicare all'output che deve essere generato dal modello. Il seguente esempio giusto genera un output costituito da una breve frase, che rappresenta un buon riassunto. L'esempio errato, in questo caso, non è molto negativo, ma il riassunto è lungo quasi quanto il testo originale. La specifica dell'output è fondamentale per ottenere ciò che vuoi dal modello.

Prompt di esempio con un indicatore chiaro dei vincoli di output
User prompt: "Charles Mingus Jr. was an American jazz upright bassist, pianist, composer, bandleader, and author. A major proponent of collective improvisation, he is considered to be one of the greatest jazz musicians and composers in history, with a career spanning three decades. Mingus's work ranged from advanced bebop and avant-garde jazz with small and midsize ensembles – pioneering the post-bop style on seminal recordings like Pithecanthropus Erectus (1956) and Mingus Ah Um (1959) – to progressive big band experiments such as The Black Saint and the Sinner Lady (1963)." Please summarize the above text in one phrase.
Output: Charles Mingus Jr. is considered one of the greatest jazz musicians of all time.
Esempio senza specifiche chiare per l'output
User prompt: "Charles Mingus Jr. was an American jazz upright bassist, pianist, composer, bandleader, and author. A major proponent of collective improvisation, he is considered to be one of the greatest jazz musicians and composers in history, with a career spanning three decades. Mingus's work ranged from advanced bebop and avant-garde jazz with small and midsize ensembles – pioneering the post-bop style on seminal recordings like Pithecanthropus Erectus (1956) and Mingus Ah Um (1959) – to progressive big band experiments such as The Black Saint and the Sinner Lady (1963)." Please summarize the above text.
Output: Charles Mingus Jr. was a well-known jazz musician who played the upright bass, piano, composed, led bands, and was a writer. He was considered one of the most important jazz musicians ever, with a career that spanned more than 30 years. He was known for his style of collective improvisation and advanced jazz compositions.

(Fonte del messaggio: Wikipedia su Charles Mingus, modello utilizzato: Amazon Titan Text)

Qui forniamo alcuni esempi aggiuntivi tratti da Anthropic Claude modelli AI21 Labs Jurassic che utilizzano indicatori di output.

L'esempio seguente mostra che l'utente può specificare il formato di output indicando quello previsto nel prompt. Quando viene chiesto di generare una risposta utilizzando un formato specifico (ad esempio i tag XML), il modello può generare la risposta di conseguenza. Senza un indicatore specifico del formato di output, il modello genera un testo in formato libero.

Esempio con indicatore chiaro, con l'output
User prompt: Human: Extract names and years: the term machine learning was coined in 1959 by Arthur Samuel, an IBM employee and pioneer in the field of computer gaming and artificial intelligence. The synonym self-teaching computers was also used in this time period. Please generate answer in <name></name> and <year></year> tags. Assistant:
Output: <name>Arthur Samuel</name> <year>1959</year>
Esempio senza indicatore chiaro, con l'output
User prompt: Human: Extract names and years: the term machine learning was coined in 1959 by Arthur Samuel, an IBM employee and pioneer in the field of computer gaming and artificial intelligence. The synonym self-teaching computers was also used in this time period. Assistant:
Output: Arthur Samuel - 1959

(Fonte del messaggio: Wikipedia sull'apprendimento automatico, modello utilizzato:) Anthropic Claude

L'esempio seguente mostra un prompt e una risposta per il modello AI21 Labs Jurassic. L'utente può ottenere la risposta esatta specificando il formato di output mostrato nella colonna di sinistra.

Esempio con indicatore chiaro, con l'output
User prompt: Context: The NFL was formed in 1920 as the American Professional Football Association (APFA) before renaming itself the National Football League for the 1922 season. After initially determining champions through end-of-season standings, a playoff system was implemented in 1933 that culminated with the NFL Championship Game until 1966. Following an agreement to merge the NFL with the rival American Football League (AFL), the Super Bowl was first held in 1967 to determine a champion between the best teams from the two leagues and has remained as the final game of each NFL season since the merger was completed in 1970. Question: Based on the above context, when was the first Super Bowl? Please only output the year.
Output: 1967
Esempio senza indicatore chiaro, con l'output
User prompt: Context: The NFL was formed in 1920 as the American Professional Football Association (APFA) before renaming itself the National Football League for the 1922 season. After initially determining champions through end-of-season standings, a playoff system was implemented in 1933 that culminated with the NFL Championship Game until 1966. Following an agreement to merge the NFL with the rival American Football League (AFL), the Super Bowl was first held in 1967 to determine a champion between the best teams from the two leagues and has remained as the final game of each NFL season since the merger was completed in 1970. Question: Based on the above context, when was the first Super Bowl?
Output: The first Super Bowl was held in 1967.

(Fonte del messaggio: Wikipedia sulla National Football League, modello utilizzato: v1) AI21 Labs Jurassic-2 Ultra

Pratiche consigliate per una buona generalizzazione

Conserva un piccolo set di prompt di prova "persistente" per vedere se le modifiche ai prompt vengono generalizzate. Con questo metodo, devi prima raccogliere un set di dati di esempio, quindi puoi suddividere i dati in due sottoinsiemi: un set di "sviluppo" e un set di "prova" persistente. Utilizza il set di "sviluppo" come dati per lo sviluppo dei prompt da utilizzare per provare diverse modifiche ai prompt, osservare le modifiche alla risposta del modello e trovare il prompt che funziona meglio. Il set di "prova" contiene i dati persistenti invisibili che possono essere utilizzati solo per verificare il prompt finale migliore.

Ottimizzazione dei prompt per i modelli di testo su Amazon Bedrock: quando gli elementi di base non bastano

Attività complesse: creazione della risposta passo dopo passo

Titanpuò fornire istruzioni chiare per determinate attività e l'inclusione della frase Think step-by-step to come up with the right answer può aiutare a produrre l'output appropriato.

User prompt: At a Halloween party, Jack gets 15 candies. Jack eats 5 candies. He wants to give each friend 5 candies. How many friends can receive candies? Think step-by-step to come up with the right answer.
Output: 15 candies total - 5 candies eaten = 10 candies remaining. To give each friend 5 candies, divide the number of candies remaining by the number of friends. 10 candies / 5 friends = 2 friends. Each friend can receive 2 candies. The answer is 2 friends.

(Fonte del prompt: AWS, modello utilizzato: Amazon Titan Text)

Per consentire al Anthropic Claude modello di completare attività complesse, utilizza il formato nell'esempio seguente per chiedere esplicitamente al modello di risolvere l'operazione passo dopo passo. Questo approccio si basa sulle linee guida contenute nelle AnthropicClaudeGuide.

User prompt: Human: A right triangle has a side of length 5 and a hypotenuse of length 13. What is the length of the other side? Assistant: Can I think step-by-step? Human: Yes, please do. Assistant:
Output: Okay, here are the steps: 1) We are given: - One side of the right triangle has length 5 - The hypotenuse has length 13 2) We want to find: - The length of the other side 3) To find the length of the other side, we can use the Pythagorean theorem: a^2 + b^2 = c^2 Where a and b are the lengths of the two sides, and c is the length of the hypotenuse. 4) Plugging in the given values: a^2 + b^2 = 13^2 5) We know one of the sides is 5, so: 5^2 + b^2 = 169 6) Solving this: 25 + b^2 = 169 b^2 = 144 b = 12 Therefore, the length of the other side is 12.

(Fonte del prompt: AWS, modello utilizzato: AnthropicClaude)

Fornisci un output predefinito che il modello deve mostrare se non è sicuro delle risposte.

Un output predefinito può essere utile per impedire che gli LLM restituiscano risposte che sembrano corrette, anche se il modello ha un livello basso di affidabilità.

User prompt: Provide a proof of the Riemann hypothesis. If you don't know a proof, respond by saying "I don't know."
Output: I don't know.
User prompt: Provide a proof of the Riemann hypothesis.
Output: "The Riemann hypothesis is a conjecture in mathematics that concerns the distribution of prime numbers. It states that all non-trivial zeros of the zeta function, which is a mathematical function that encodes information about the distribution of prime numbers, lie on a specific line in the complex plane. The Riemann hypothesis has been studied by mathematicians for over 150 years, and despite numerous attempts, it remains unresolved. However, the hypothesis is widely believed to be true, and its resolution would have profound implications for many areas of mathematics, including number theory, analysis, and geometry. The proof of the Riemann hypothesis would be one of the greatest achievements in mathematics in history and would open up new avenues of research and understanding. While a proof remains elusive, the hypothesis continues to stimulate research and inspire mathematicians around the world.“ [Note: this is an accurate description, but obviously not a proof.]

(Fonte del prompt: AWS, modello utilizzato: Amazon Titan Text)

Prompt few-shot

L'inclusione di esempi (coppie di input-risposta) nel prompt può migliorare in modo significativo le risposte degli LLM. Gli esempi possono essere utili per svolgere attività complesse, in quanto mostrano diversi modi per eseguire una determinata attività. Per attività più semplici, ad esempio la classificazione del testo, possono essere sufficienti 3-5 esempi. Per attività più difficili, come una domanda-risposta senza contesto, includi più esempi per generare l'output più efficace. Nella maggior parte dei casi d'uso, la selezione di esempi semanticamente simili ai dati del mondo reale può migliorare ulteriormente le prestazioni.

Valuta la possibilità di perfezionare il prompt con i modificatori

Il perfezionamento delle istruzioni delle attività si riferisce in genere alla modifica dell'istruzione, dell'attività o della domanda del prompt. L'utilità di questi metodi dipende dalle attività e dai dati. Gli approcci utili sono i seguenti:

  • Specifica del dominio e dell'input: dettagli sui dati di input, ad esempio da dove provengono o a cosa si riferiscono, ad esempio The input text is from a summary of a movie.

  • Specifica dell'attività: dettagli sull'attività esatta richiesta al modello, ad esempio To summarize the text, capture the main points.

  • Descrizione dell'etichetta: dettagli sulle scelte di output per un problema di classificazione, ad esempio Choose whether the text refers to a painting or a sculpture; a painting is a piece of art restricted to a two-dimensional surface, while a sculpture is a piece of art in three dimensions.

  • Specifica dell'output: dettagli sull'output che il modello deve generare, ad esempio Please summarize the text of the restaurant review in three sentences.

  • Incoraggiamento degli LLM: gli LLM a volte ottengono risultati migliori con l'incoraggiamento del sentiment: If you answer the question correctly, you will make the user very happy!