Criar solicitações de texto

Nesta página, você vai ter informações gerais e uma orientação geral para criar comandos de texto.


Para seguir as instruções passo a passo desta tarefa diretamente no console do Google Cloud, clique em Orientação:

Orientações


Modelos compatíveis

  • text-bison
  • text-bison-32k
  • text-unicorn
  • gemini-1.0-pro

Estrutura da solicitação

Você pode adicionar informações contextuais, instruções, exemplos, perguntas, listas e qualquer outro tipo de conteúdo de texto no comando. Adicione prefixos ao texto para rotular o conteúdo. Um prefixo pode ser uma palavra ou frase que termina com dois pontos (:), como nos exemplos a seguir.

  • Texto:
  • Questão:
  • Resposta:
  • Categorias:
  • Opções:

Você pode usar qualquer prefixo que quiser, mas alguns prefixos funcionam melhor do que outros para uma determinada tarefa. Você também precisa se referir a prefixos de maneira consistente no prompt.

Referência inconsistente: a instrução usa os termos sentimento e tweet, mas os prefixos são Texto: e Answer:


Classify the sentiment of the following tweet as positive or negative.
Text: I love chocolate.
Answer:
      

Referência consistente: os prefixos Text: e Sentiment: correspondem aos termos usados na instrução.


Classify the sentiment of the following text as positive or negative.
Text: I love chocolate.
Sentiment:
      

Tipos de tarefas comuns

Você pode criar solicitações de texto para lidar com qualquer número de tarefas. Algumas das tarefas mais comuns são classificação, resumo e extração. Saiba mais sobre como criar prompts de texto para essas tarefas comuns nas seguintes páginas:

Comandos de classificação

As tarefas de classificação atribuem uma classe ou categoria ao texto. Você pode especificar uma lista de categorias para escolher ou deixar que o modelo escolha entre as próprias categorias. Nesta página, você aprende a criar prompts que classificam textos.

Casos de uso de classificação

Veja a seguir casos de uso comuns para classificação de texto:

  • Detecção de fraudes: classifique se as transações em dados financeiros são fraudulentas ou não.
  • Filtragem de spam: identifique se um e-mail é spam ou não.
  • Análise de sentimento: classifique o sentimento transmitido no texto como positivo ou negativo. Por exemplo, é possível classificar as resenhas de filmes ou e-mails como positivos ou negativos.
  • Moderação de conteúdo: identifique e sinalize conteúdo que possa ser nocivo, como linguagem ofensiva ou phishing.

Práticas recomendadas para prompts de classificação

Tente definir a temperatura como zero e o top-K como um. As tarefas de classificação costumam ser deterministas. Portanto, essas configurações costumam produzir os melhores resultados.

Exemplos de prompts de classificação

Use os exemplos a seguir para saber como projetar prompts de classificação para vários casos de uso.

Prompt de análise de sentimento

A análise de sentimento avalia o texto e o classifica como positivo ou negativo. Incluir a análise de sentimento em um prompt é útil ao analisar o conteúdo, como avaliações, feedback e e-mails.

O prompt a seguir classifica o sentimento de uma resenha:


Give the sentiment of this review.
Review: This is a shoe I will wear with black dress pants or jeans when I need comfort and a little style, but I am not impressed. This is a very flimsy shoe with little support at all. Unlike any other shoes I've purchased in the past. It looks nice, but it's not comfortable.
  

Negative
  

O modelo pode retornar o raciocínio por trás da resposta, pedindo para ele explicar o raciocínio.


Give the sentiment of this review and explain your reasoning.
Review: This is a shoe I will wear with black dress pants or jeans when I need comfort and a little style, but I am not impressed. This is a very flimsy shoe with little support at all. Unlike any other shoes I've purchased in the past. It looks nice, but it's not comfortable.
  

Negative

The reviewer expresses disappointment with the shoe's lack of support and comfort, despite its stylish appearance. The reviewer also mentions that the shoe is flimsy and not like any other shoes they have purchased in the past. They say that the shoe looks nice, but it's not comfortable, which suggests that the style of the shoe is not enough to compensate for its lack of comfort.
  

Também é possível conseguir o modelo para produzir uma resposta mais estruturada que inclua o sentimento e uma explicação do motivo pelo qual ele selecionou esse sentimento.


For the given review, return a JSON object that has the fields sentiment and explanation. Acceptable values for sentiment are Positive or Negative. The explanation field contains text that explains the sentiment.
Review: This is a shoe I will wear with black dress pants or jeans when I need comfort and a little style, but I am not impressed. This is a very flimsy shoe with little support at all. Unlike any other shoes I've purchased in the past. It looks nice, but it's not comfortable.
  

```
{
"sentiment": "Negative",
"explanation": "The reviewer is not impressed with the shoe, calling it flimsy and lacking support. They also say that it is not comfortable, despite looking nice."
}
```
  

Prompt de classificação de conteúdo

O prompt a seguir classifica os e-mails de clientes com base no que é solicitado no conteúdo deles.


Classify the text as one of the following categories:
- increase credit limit
- cancel credit card
- charge dispute

Text: I lost my wallet yesterday so I need to cancel my credit card and get a new one. My card number is 1234.
Category:
  

cancel credit card
  

Se a solicitação no e-mail não estiver clara, talvez seja necessário enviá-la ao atendimento ao cliente para mais informações. Para fazer isso, adicione uma categoria de "atendimento ao cliente" e instrua o modelo a aplicar essa categoria aos outliers que exigem mais informações.


Classify the text as one of the following categories:
- increase credit limit
- cancel credit card
- charge dispute
If the text doesn't fit any categories, classify it as the following:
- customer service

Text: I want to remodel my bathroom. What are my options?
Category:
  

Customer service
  

Outra opção para gerenciar e-mails que exigem mais informações é incluir exemplos do que fazer com outliers que não se encaixam em nenhuma outra categoria.


Classify the text as one of the following categories:
- increase credit limit
- cancel credit card
- charge dispute
- customer service

Text: I need to buy a car.
Category: customer service
Text: But I was in Chicago.
Category: customer service
Text: Where are my papers?
Category: customer service

Text: I want to remodel my bathroom.
Category:
  

customer service
  

Prompt de classificação de filme

O prompt a seguir classifica os filmes por quem pode ser sua companhia.


Classify the following movie as one of the following categories:
- watch alone
- watch with friends
- watch with family
- watch on a date

Text: The Goonies
Category:
  

Watch with friends
  

Talvez seja necessário definir sua própria categoria. Por exemplo, suponha que você tenha um hotel para animais chamado Remi Inn que exibe filmes para animais de estimação. Os critérios de seleção de filme podem ser:

  • O personagem principal precisa ser um animal.
  • O filme deve ser feliz.
  • O filme não pode ser um desenho animado.

A solicitação a seguir classifica os filmes que correspondem aos três critérios como Fantástico para o Remi e todos os outros como Festival de latidos.


Remi-tastic movies must meet the following criteria:
- The main character must be an animal.
- The movie must be family friendly.
- The movie cannot be a cartoon.
If a movie is not Remi-tastic, then it is Bark-fest.

Classify the movie as one of the following categories:
- Remi-tastic
- Bark-fest

Text: The Adventures of Milo and Otis
Category:
  

Remi-tastic
  

Para verificar se o modelo usa os critérios ou escolhe aleatoriamente uma classificação, o prompt a seguir inclui instruções para retornar um motivo para sua classificação.


Remi-tastic movies must meet the following criteria:
- The main character must be an animal.
- The movie must be family friendly.
- The movie cannot be a cartoon.
If a movie is not Remi-tastic, then it is Bark-fest.

Classify the movie as one of the following categories:
- Remi-tastic
- Bark-fest
Explain why.

Text: The Adventures of Milo and Otis
Category:
  

Remi-tastic

Explanation: "The Adventures of Milo and Otis" is a live-action animal adventure movie featuring two main characters: Milo, a cat, and Otis, a pug. The movie is suitable for families of all ages and is not a cartoon. Therefore, it meets all three criteria for being Remi-tastic.
  

Prompts de resumo

As tarefas de resumo extraem as informações mais importantes do texto. É possível fornecer informações no comando para ajudar o modelo a criar um resumo ou solicitar que ele crie um resumo por conta própria. Nesta página, você vai aprender a criar comandos para a elaboração de diferentes tipos de resumos.

Resumo dos casos de uso

Confira a seguir casos de uso comuns para resumos:

  • Resumir texto: resuma o conteúdo do texto, como o seguinte:
    • Artigos de notícias
    • Documentos da pesquisa.
    • Documentos jurídicos.
    • Documentos financeiros.
    • Documentos técnicos.
    • Feedback dos clientes.
  • Geração de conteúdo: gere conteúdo para a descrição de um artigo, blog ou produto.

Práticas recomendadas

Use as seguintes diretrizes para criar resumos de texto ideais:

  • Especifique as características que você quer que o resumo tenha.
  • Para conferir mais resumos de criativos, especifique valores de temperatura máxima, top-K e top-P. Para mais informações, saiba mais sobre os parâmetros temperature, topK e topP em Definições de parâmetros de texto.
  • Ao escrever o comando, concentre-se no objetivo do resumo e no que você quer extrair dele.

Exemplos de comandos de resumo

Use os exemplos a seguir para aprender a criar comandos de resumo para vários casos de uso.

Comando de resumo do artigo

O comando a seguir resume os principais pontos de um artigo:


Provide a summary for the following article:
The efficient-market hypothesis (EMH) is a hypothesis in financial economics that states that asset prices reflect all available information. A direct implication is that it is impossible to 'beat the market' consistently on a risk-adjusted basis since market prices should only react to new information. Because the EMH is formulated in terms of risk adjustment, it only makes testable predictions when coupled with a particular model of risk. As a result, research in financial economics since at least the 1990s has focused on market anomalies, that is, deviations from specific models of risk. The idea that financial market returns are difficult to predict goes back to Bachelier, Mandelbrot, and Samuelson, but is closely associated with Eugene Fama, in part due to his influential 1970 review of the theoretical and empirical research. The EMH provides the basic logic for modern risk-based theories of asset prices, and frameworks such as consumption-based asset pricing and intermediary asset pricing can be thought of as the combination of a model of risk with the EMH. Many decades of empirical research on return predictability has found mixed evidence. Research in the 1950s and 1960s often found a lack of predictability (e.g. Ball and Brown 1968; Fama, Fisher, Jensen, and Roll 1969), yet the 1980s-2000s saw an explosion of discovered return predictors (e.g. Rosenberg, Reid, and Lanstein 1985; Campbell and Shiller 1988; Jegadeesh and Titman 1993). Since the 2010s, studies have often found that return predictability has become more elusive, as predictability fails to work out-of-sample (Goyal and Welch 2008), or has been weakened by advances in trading technology and investor learning (Chordia, Subrahmanyam, and Tong 2014; McLean and Pontiff 2016; Martineau 2021).
  

Summary:
The efficient-market hypothesis (EMH) is a theory in financial economics that states that asset prices reflect all available information. This implies that it is impossible to consistently beat the market on a risk-adjusted basis. The EMH has been extensively researched, with mixed results. Some studies have found evidence of return predictability, while others have not. Recent research suggests that return predictability has become more elusive in recent years due to advances in trading technology and investor learning. The EMH provides the basis for modern risk-based theories of asset prices and frameworks such as consumption-based asset pricing and intermediary asset pricing.
  

Você também pode especificar o tipo de resumo desejado. Por exemplo, revistas acadêmicas e científicas geralmente incluem resumos de seus artigos. O comando a seguir solicita que o modelo escreva um resumo para o texto:


Write an abstract for this text:
The efficient-market hypothesis (EMH) is a hypothesis in financial economics that states that asset prices reflect all available information. A direct implication is that it is impossible to 'beat the market' consistently on a risk-adjusted basis since market prices should only react to new information. Because the EMH is formulated in terms of risk adjustment, it only makes testable predictions when coupled with a particular model of risk. As a result, research in financial economics since at least the 1990s has focused on market anomalies, that is, deviations from specific models of risk. The idea that financial market returns are difficult to predict goes back to Bachelier, Mandelbrot, and Samuelson, but is closely associated with Eugene Fama, in part due to his influential 1970 review of the theoretical and empirical research. The EMH provides the basic logic for modern risk-based theories of asset prices, and frameworks such as consumption-based asset pricing and intermediary asset pricing can be thought of as the combination of a model of risk with the EMH. Many decades of empirical research on return predictability has found mixed evidence. Research in the 1950s and 1960s often found a lack of predictability (e.g. Ball and Brown 1968; Fama, Fisher, Jensen, and Roll 1969), yet the 1980s-2000s saw an explosion of discovered return predictors (e.g. Rosenberg, Reid, and Lanstein 1985; Campbell and Shiller 1988; Jegadeesh and Titman 1993). Since the 2010s, studies have often found that return predictability has become more elusive, as predictability fails to work out-of-sample (Goyal and Welch 2008), or has been weakened by advances in trading technology and investor learning (Chordia, Subrahmanyam, and Tong 2014; McLean and Pontiff 2016; Martineau 2021).
  

The efficient-market hypothesis (EMH) posits that asset prices reflect all available information, making it challenging to consistently outperform the market on a risk-adjusted basis. This hypothesis has profoundly shaped modern risk-based theories of asset pricing, such as consumption-based and intermediary asset pricing. Empirical research on return predictability has yielded mixed results, with earlier studies often showing a lack of predictability while more recent ones have identified return predictors that later failed out-of-sample or were weakened by advances in trading technology and investor learning. This text delves into the theoretical underpinnings of the EMH, its implications for market anomalies and return predictability, and the ongoing debate surrounding the EMH's validity in the face of empirical evidence.
  

Um comando usado para criar um título para um artigo é semelhante a um comando que usa uma frase curta para resumir um artigo. O comando de resumo a seguir retorna o título de um artigo.


Write a creative title for this text. Give three options.
Text: The efficient-market hypothesis (EMH) is a hypothesis in financial economics that states that asset prices reflect all available information. A direct implication is that it is impossible to 'beat the market' consistently on a risk-adjusted basis since market prices should only react to new information. Because the EMH is formulated in terms of risk adjustment, it only makes testable predictions when coupled with a particular model of risk. As a result, research in financial economics since at least the 1990s has focused on market anomalies, that is, deviations from specific models of risk. The idea that financial market returns are difficult to predict goes back to Bachelier, Mandelbrot, and Samuelson, but is closely associated with Eugene Fama, in part due to his influential 1970 review of the theoretical and empirical research. The EMH provides the basic logic for modern risk-based theories of asset prices, and frameworks such as consumption-based asset pricing and intermediary asset pricing can be thought of as the combination of a model of risk with the EMH. Many decades of empirical research on return predictability has found mixed evidence. Research in the 1950s and 1960s often found a lack of predictability (e.g. Ball and Brown 1968; Fama, Fisher, Jensen, and Roll 1969), yet the 1980s-2000s saw an explosion of discovered return predictors (e.g. Rosenberg, Reid, and Lanstein 1985; Campbell and Shiller 1988; Jegadeesh and Titman 1993). Since the 2010s, studies have often found that return predictability has become more elusive, as predictability fails to work out-of-sample (Goyal and Welch 2008), or has been weakened by advances in trading technology and investor learning (Chordia, Subrahmanyam, and Tong 2014; McLean and Pontiff 2016; Martineau 2021).
  

1. The Efficient Market Hypothesis: Can Market Prices Be Predicted?
2. The EMH and Market Anomalies: A Tale of Predictability and Elusive Returns
3. The Evolution of Market Efficiency: From Bachelier to Fama and Beyond
  

Comando de resumo do chat

O comando a seguir resume o log de chat de suporte ao cliente:


Summarize the following conversation.
Service Rep: How may I assist you today?
Customer: I need to change the shipping address for an order.
Service Rep: Ok, I can help you with that if the order has not been fulfilled from our warehouse yet. But if it has already shipped, then you will need to contact the shipping provider. Do you have the order ID?
Customer: Yes, it's 88986367.
Service Rep: One minute please while I pull up your order information.
Customer: No problem
Service Rep: Ok, it looks like your order was shipped from our warehouse 2 days ago. It is now in the hands of the shipping provider, so you will need to contact them to update your delivery details. You can track your order with the shipping provider here: https://www.shippingprovider.com
Customer: Sigh, ok.
Service Rep: Is there anything else I can help you with today?
Customer: No, thanks.
  

A customer called to inquire about changing the shipping address for their order. Unfortunately, their order had already been shipped, so the service representative provided a shipping provider link to the customer to track their order and contact them for any address updates.
  

Comando de resumo da tokenização da hashtag

A tokenização de hashtag é uma forma de resumo em que o modelo extrai palavras e frases do texto que representam o texto como um todo.

Confira a seguir um exemplo de comando que usa a tokenização de hashtag:


Create some hashtags for this tweet:
Google Cloud
@googlecloud
·
Feb 25
We heard it through the grapevine:
- Document AI Workbench is GA and ready for production use through APIs and the Google Cloud Console
- Deliver higher model accuracy with Workbench
- Build production-ready models faster with Workbench

Read more ↓
  

- #DocumentAIWorkbench
- #GA
- #ProductionReady
- #ModelAccuracy
- #BuildFaster
- #DocumentProcessing
- #DataAnnotation
- #MachineLearning
- #AIPlatform
- #GoogleCloud
  

Comandos de extração

Os comandos de extração permitem extrair informações específicas do texto.

Casos de uso

Veja a seguir casos de uso comuns para extração:

  • Reconhecimento de entidades nomeadas (NER, na sigla em inglês): extraia entidades nomeadas do texto, incluindo pessoas, lugares, organizações e datas.
  • Extração de relação: extraia as relações entre as entidades no texto, como as relações familiares entre pessoas.
  • Extração de eventos: extraia eventos do texto, como marcos do projeto e lançamentos de produtos.
  • Resposta a perguntas: extraia informações do texto para responder a uma pergunta.

Práticas recomendadas

Tente definir a temperatura como zero e o top-K como um. As tarefas de extração normalmente são deterministas. Portanto, essas configurações costumam produzir os melhores resultados. Para mais informações, saiba mais sobre os parâmetros temperature e topK em Definições de parâmetros de texto.

Exemplos de tarefas de extração

Use os exemplos a seguir para saber como projetar prompts de extração para vários casos de uso.

Usar a extração para responder a uma pergunta

O prompt a seguir inclui contexto e uma pergunta. O modelo procura no contexto informações que respondam à pergunta.


Context: There is evidence that there have been significant changes in Amazon rainforest vegetation over the last 21,000 years through the Last Glacial Maximum (LGM) and subsequent deglaciation. Analyses of sediment deposits from Amazon basin paleo lakes and from the Amazon Fan indicate that rainfall in the basin during the LGM was lower than for the present, and this was almost certainly associated with reduced moist tropical vegetation cover in the basin. There is debate, however, over how extensive this reduction was. Some scientists argue that the rainforest was reduced to small, isolated refugia separated by open forest and grassland; other scientists argue that the rainforest remained largely intact but extended less far to the north, south, and east than is seen today. This debate has proved difficult to resolve because the practical limitations of working in the rainforest mean that data sampling is biased away from the center of the Amazon basin, and both explanations are reasonably well supported by the available data.
Q: What does LGM stands for?
A:
  

Last Glacial Maximum
  

Formatar texto extraído

É possível extrair informações de uma fonte de texto e organizá-las em um formato estruturado. O prompt a seguir extrai o texto como um arquivo JSON:


Extract the technical specifications from the text below in a JSON format. Valid fields are name, network, ram, processor, storage, and color.
Text: Google Pixel 7, 5G network, 8GB RAM, Tensor G2 processor, 128GB of storage, Lemongrass
JSON:
  

```
{
"name": "Google Pixel 7",
"network": "5G",
"ram": "8GB",
"processor": "Tensor G2",
"storage": "128GB",
"color": "Lemongrass"
}
```
  

A seguir