Diseña instrucciones de texto

En esta página, se proporciona una descripción y orientación general para textos de instrucción.


Para seguir la guía paso a paso sobre esta tarea de forma directa en la consola de Google Cloud, haz clic en Guiarme:

GUIARME


Modelos compatibles

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

Estructura del mensaje

Puedes agregarle instrucciones, ejemplos, preguntas, listas y cualquier otro tipo de contenido de texto que se te ocurra a las instrucciones para dar información contextual. Etiqueta el contenido del texto al agregar prefijos. Un prefijo puede ser una palabra o una frase que termina con dos puntos (:), como en los siguientes ejemplos.

  • Texto:
  • Pregunta:
  • Respuesta:
  • Categorías:
  • Opciones:

Puedes usar los prefijos que desees, pero es posible que algunos funcionen mejor que otros para una tarea determinada. También debes asegurarte de hacer referencia a los prefijos de forma coherente dentro del mensaje.

Referencia incoherente: la instrucción usa los términos opinión y tuit, pero los prefijos son Texto: y Respuesta:.


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

Referencia coherente: Los prefijos Text: y Opiniones: coinciden con los términos usados en la instrucción.


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

Tipos comunes de tareas

Puedes crear mensajes de texto para controlar cualquier cantidad de tareas. Algunas de las tareas más comunes son la clasificación, el resumen y la extracción. Puedes obtener más información sobre el diseño de mensajes de texto para estas tareas comunes en las siguientes páginas:

Instrucciones de clasificación

Las tareas de clasificación asignan una clase o categoría al texto. Puedes especificar una lista de categorías desde la cual elegir o permitir que el modelo elija una de sus propias categorías. En esta página, aprenderás a crear instrucciones para clasificar textos.

Casos de uso de clasificación

Los siguientes son casos de uso comunes para la clasificación de textos:

  • Detección de fraudes: Clasifica si las transacciones en datos financieros son fraudulentas o no.
  • Filtro de spam: Identifica si un correo electrónico es spam o no.
  • Análisis de opiniones: Clasifica la opinión que se transmite en el texto como positiva o negativa. Por ejemplo, puedes clasificar las opiniones sobre películas o los correos electrónicos como positivos o negativos.
  • Moderación de contenido: Identifica y marca el contenido que pueda ser perjudicial, como el lenguaje ofensivo o phishing.

Prácticas recomendadas para los mensajes de clasificación

Establece la temperatura en cero y K superior en uno. Las tareas de clasificación suelen ser determinísticas, por lo que esta configuración suele producir los mejores resultados.

Ejemplos de mensajes de clasificación

Usa los siguientes ejemplos con el fin de obtener información para diseñar mensajes de clasificación para varios casos de uso.

Instrucción de análisis de opiniones

El análisis de opiniones evalúa el texto y lo clasifica como positivo o negativo. Incluir el análisis de opiniones en una instrucción es útil cuando se analiza contenido como opiniones, comentarios y correos electrónicos.

En el siguiente mensaje, se clasifica la opinión de una revisión:


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
  

Puedes hacer que el modelo muestre el razonamiento detrás de su respuesta si le indicas que explique su razonamiento.


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.
  

También puedes obtener el modelo para producir una respuesta más estructurada que incluya la opinión y una explicación del motivo por el que se seleccionó esa opinión.


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."
}
```
  

Instrucción de clasificación de contenido

El siguiente mensaje clasifica los correos electrónicos de los clientes según lo que se solicita en su contenido.


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
  

Si la solicitud en el correo electrónico no es clara, es posible que debas enviarla al servicio de atención al cliente para obtener más información. Para ello, agrega una categoría de “servicio de atención al cliente” y, luego, indica al modelo que aplique esta categoría a los valores atípicos que requieren más información.


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
  

Otra opción para manejar los correos electrónicos que requieren más información es incluir ejemplos de qué hacer con valores atípicos que no encajan en ninguna otra categoría.


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
  

Instrucción de clasificación de películas

En el siguiente mensaje, se clasifican las películas con quién debes mirarlas.


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
  

Es posible que debas definir tu propia categoría. Por ejemplo, supongamos que tienes un hotel de mascotas llamado Remi Inn que muestra películas para mascotas. Los criterios de selección de la película podrían ser:

  • El personaje principal debe ser un animal.
  • La película debe ser feliz.
  • La película no puede ser de dibujos animados.

El siguiente mensaje clasifica las películas que coinciden con los tres criterios como Remi-tastic y todas las demás como Bark-fest.


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
  

A fin de verificar si el modelo usa los criterios o elige una clasificación de forma aleatoria, en la siguiente instrucción, se incluyen instrucciones para mostrar un motivo de su clasificación.


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.
  

Instrucciones de resumen

Las tareas de resumen extraen la información más importante del texto. Puedes proporcionar información en la instrucción para ayudar al modelo a crear un resumen. También puedes pedirle al modelo que cree un resumen por sí solo. En esta página, aprenderás a diseñar instrucciones para crear diferentes tipos de resúmenes.

Resumen de los casos de uso

Los siguientes son casos de uso comunes para resúmenes.

  • Resume el texto: Resume el contenido de un texto como los siguientes:
    • Artículos de noticias.
    • Trabajos de investigación.
    • Documentos legales.
    • Documentos financieros.
    • Documentos técnicos.
    • Comentarios del cliente.
  • Generación de contenido: Genera contenido para un artículo, blog o descripción del producto.

Prácticas recomendadas

Usa los siguientes lineamientos para crear resúmenes de texto óptimos:

  • Especifica las características que quieres que tenga el resumen.
  • Para obtener más resúmenes de creatividades, especifica valores de temperatura más altos, de K y más P. Para obtener más información, consulta los parámetros temperature, topK y topP en Definiciones de parámetros de texto.
  • Cuando escribas la instrucción, enfócate en el propósito del resumen y lo que deseas obtener de él.

Ejemplos de instrucciones de resumen

Usa los siguientes ejemplos a fin de aprender a diseñar instrucciones de resumen para varios casos de uso.

Instrucción de resumen de artículo

La siguiente instrucción resume los puntos principales de un artículo:


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.
  

También puedes especificar el tipo de resumen que desees. Por ejemplo, las revistas académicas y científicas suelen incluir resúmenes de sus artículos. En el siguiente mensaje, se le pide al modelo que escriba un resumen para el 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.
  

Un mensaje que se usa para crear un título para un artículo es similar a uno que usa una frase corta para resumir un artículo. La siguiente instrucción de resumen muestra un título para un artículo.


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
  

Mensaje de resumen de chat

La siguiente instrucción resume un registro del chat de asistencia al 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.
  

Mensaje de resumen de asignación de token de hash

La asignación de token de hashtag es una forma de resumen en la que el modelo extrae palabras y frases del texto que son representativas del texto en su totalidad.

El siguiente es un ejemplo de un mensaje que usa la asignación de token 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
  

Instrucción de extracción

Las instrucciones de extracción te permiten extraer información específica del texto.

Casos de uso

Los siguientes son casos de uso comunes de extracción:

  • Reconocimiento de entidades con nombre (NER): Extrae entidades con nombre de texto, incluidas personas, lugares, organizaciones y fechas.
  • Extracción de relaciones: Extrae las relaciones entre entidades en texto, como las relaciones familiares entre personas.
  • Extracción de eventos: Extrae eventos de texto, como eventos importantes de proyectos y lanzamientos de productos.
  • Respuesta de preguntas: Extrae información del texto para responder una pregunta.

Prácticas recomendadas

Establece la temperatura en cero y K superior en uno. Las tareas de extracción suelen ser determinísticas, por lo que esta configuración suele producir los mejores resultados. Para obtener más información, consulta los parámetros temperature y topK en Definiciones de parámetros de texto .

Ejemplos de tareas de extracción

Usa los siguientes ejemplos a fin de aprender a diseñar mensajes de extracción para varios casos de uso.

Usa la extracción para responder una pregunta

En el siguiente mensaje, se incluye contexto y una pregunta. El modelo busca en el contexto información que responda la pregunta.


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
  

Formato de texto extraído

Puedes extraer información de una fuente de texto y organizarla en un formato estructurado. En el siguiente mensaje, se da formato al texto extraído como un archivo 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"
}
```
  

¿Qué sigue?