Use instruções do sistema

Este documento descreve como usar as instruções do sistema. Para saber o que são as instruções do sistema e as práticas recomendadas para as usar, consulte o artigo Introdução às instruções do sistema.

As instruções do sistema são um conjunto de instruções que o modelo processa antes de processar comandos. Recomendamos que use instruções do sistema para indicar ao modelo como quer que se comporte e responda aos comandos. Por exemplo, pode incluir elementos como a função ou a personagem, informações contextuais e instruções de formatação:

You are a friendly and helpful assistant.
Ensure your answers are complete, unless the user requests a more concise approach.
When generating code, offer explanations for code segments as necessary and maintain good coding practices.
When presented with inquiries seeking information, provide answers that reflect a deep understanding of the field, guaranteeing their correctness.
For any non-english queries, respond in the same language as the prompt unless otherwise specified by the user.
For prompts involving reasoning, provide a clear explanation of each step in the reasoning process before presenting the final answer.

Quando uma instrução do sistema é definida, aplica-se a todo o pedido. Funciona em várias interações do utilizador e do modelo quando incluído no comando. Embora as instruções do sistema sejam separadas do conteúdo do comando, continuam a fazer parte dos seus comandos gerais e, por isso, estão sujeitas às políticas de utilização de dados padrão.

Exemplos de utilização

Pode usar instruções do sistema de várias formas, incluindo:

  • Definir um perfil fictício ou uma função (por exemplo, para um chatbot)
  • Definir o formato de saída (Markdown, YAML, etc.)
  • Definir o estilo e o tom do resultado (por exemplo, detalhe, formalidade e nível de leitura alvo)
  • Definir objetivos ou regras para a tarefa (por exemplo, devolver um fragmento de código sem mais explicações)
  • Fornecer contexto adicional para o comando (por exemplo, um limite de conhecimentos)
  • Especificar em que idioma o modelo deve responder (por vezes, os modelos podem responder no seu idioma local, mesmo que o comando seja escrito noutro idioma). Quando usa um idioma diferente do inglês para os seus comandos, recomendamos que adicione o seguinte às instruções do sistema:

    All questions should be answered comprehensively with details, unless the user requests a concise response specifically. Respond in the same language as the query.
    

Exemplos de código

Os exemplos de código nos separadores seguintes demonstram como usar instruções do sistema na sua aplicação de IA generativa.

Python

Instalação

pip install --upgrade google-genai

Para saber mais, consulte a documentação de referência do SDK.

Defina variáveis de ambiente para usar o SDK de IA generativa com o Vertex AI:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_VERTEXAI=True

from google import genai
from google.genai.types import GenerateContentConfig, HttpOptions

client = genai.Client(http_options=HttpOptions(api_version="v1"))
response = client.models.generate_content(
    model="gemini-2.5-flash",
    contents="Why is the sky blue?",
    config=GenerateContentConfig(
        system_instruction=[
            "You're a language translator.",
            "Your mission is to translate text in English to French.",
        ]
    ),
)
print(response.text)
# Example response:
# Pourquoi le ciel est-il bleu ?

Go

Saiba como instalar ou atualizar o Go.

Para saber mais, consulte a documentação de referência do SDK.

Defina variáveis de ambiente para usar o SDK de IA generativa com o Vertex AI:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_VERTEXAI=True

import (
	"context"
	"fmt"
	"io"

	genai "google.golang.org/genai"
)

// generateWithSystem shows how to generate text using a text prompt and system instruction.
func generateWithSystem(w io.Writer) error {
	ctx := context.Background()

	client, err := genai.NewClient(ctx, &genai.ClientConfig{
		HTTPOptions: genai.HTTPOptions{APIVersion: "v1"},
	})
	if err != nil {
		return fmt.Errorf("failed to create genai client: %w", err)
	}

	modelName := "gemini-2.5-flash"
	contents := genai.Text("Why is the sky blue?")
	config := &genai.GenerateContentConfig{
		SystemInstruction: &genai.Content{
			Parts: []*genai.Part{
				{Text: "You're a language translator. Your mission is to translate text in English to French."},
			},
		},
	}

	resp, err := client.Models.GenerateContent(ctx, modelName, contents, config)
	if err != nil {
		return fmt.Errorf("failed to generate content: %w", err)
	}

	respText := resp.Text()

	fmt.Fprintln(w, respText)

	// Example response:
	// Pourquoi le ciel est-il bleu ?

	return nil
}

Node.js

Instalação

npm install @google/genai

Para saber mais, consulte a documentação de referência do SDK.

Defina variáveis de ambiente para usar o SDK de IA generativa com o Vertex AI:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_VERTEXAI=True

const {GoogleGenAI} = require('@google/genai');

const GOOGLE_CLOUD_PROJECT = process.env.GOOGLE_CLOUD_PROJECT;
const GOOGLE_CLOUD_LOCATION = process.env.GOOGLE_CLOUD_LOCATION || 'global';

async function generateContent(
  projectId = GOOGLE_CLOUD_PROJECT,
  location = GOOGLE_CLOUD_LOCATION
) {
  const client = new GoogleGenAI({
    vertexai: true,
    project: projectId,
    location: location,
  });

  const prompt = `
  User input: I like bagels.
  Answer:
  `;

  const response = await client.models.generateContent({
    model: 'gemini-2.5-flash',
    contents: prompt,
    config: {
      systemInstruction: [
        'You are a language translator.',
        'Your mission is to translate text in English to French.',
      ],
    },
  });

  console.log(response.text);

  return response.text;
}

Java

Saiba como instalar ou atualizar o Java.

Para saber mais, consulte a documentação de referência do SDK.

Defina variáveis de ambiente para usar o SDK de IA generativa com o Vertex AI:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_VERTEXAI=True


import com.google.genai.Client;
import com.google.genai.types.Content;
import com.google.genai.types.GenerateContentConfig;
import com.google.genai.types.GenerateContentResponse;
import com.google.genai.types.HttpOptions;
import com.google.genai.types.Part;

public class TextGenerationWithSystemInstruction {

  public static void main(String[] args) {
    // TODO(developer): Replace these variables before running the sample.
    String modelId = "gemini-2.5-flash";
    generateContent(modelId);
  }

  // Generates text with text and system instruction input
  public static String generateContent(String modelId) {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (Client client =
        Client.builder()
            .location("global")
            .vertexAI(true)
            .httpOptions(HttpOptions.builder().apiVersion("v1").build())
            .build()) {

      GenerateContentConfig config =
          GenerateContentConfig.builder()
              .systemInstruction(
                  Content.fromParts(
                      Part.fromText("You're a language translator."),
                      Part.fromText("Your mission is to translate text in English to French.")))
              .build();

      GenerateContentResponse response =
          client.models.generateContent(modelId, "Why is the sky blue?", config);

      System.out.print(response.text());
      // Example response:
      // Pourquoi le ciel est-il bleu ?
      return response.text();
    }
  }
}

REST

Depois de configurar o seu ambiente, pode usar a API REST para testar um comando de texto. O exemplo seguinte envia um pedido para o ponto final do modelo do publicador.

Antes de usar qualquer um dos dados do pedido, faça as seguintes substituições:

  • GENERATE_RESPONSE_METHOD: o tipo de resposta que quer que o modelo gere. Escolha um método que gere a forma como quer que a resposta do modelo seja devolvida:
    • streamGenerateContent: a resposta é transmitida à medida que é gerada para reduzir a perceção de latência para um público humano.
    • generateContent: a resposta é devolvida depois de ser totalmente gerada.
  • LOCATION: a região para processar o pedido. As opções disponíveis incluem o seguinte:

    Clique para expandir uma lista parcial das regiões disponíveis

    • us-central1
    • us-west4
    • northamerica-northeast1
    • us-east4
    • us-west1
    • asia-northeast3
    • asia-southeast1
    • asia-northeast1
  • PROJECT_ID: o seu ID do projeto.
  • MODEL_ID: o ID do modelo multimodal que quer usar.
  • ROLE: A função numa conversa associada ao conteúdo. É necessário especificar uma função, mesmo em exemplos de utilização de uma única interação. Os valores aceitáveis incluem o seguinte:
    • USER: especifica o conteúdo enviado por si.
    • MODEL: especifica a resposta do modelo.
  • TEXT
    As instruções de texto a incluir no comando. Por exemplo, User input: I like bagels.
  • SAFETY_CATEGORY: A categoria de segurança para a qual configurar um limite. Os valores aceitáveis incluem o seguinte:

    Clique para expandir as categorias de segurança

    • HARM_CATEGORY_SEXUALLY_EXPLICIT
    • HARM_CATEGORY_HATE_SPEECH
    • HARM_CATEGORY_HARASSMENT
    • HARM_CATEGORY_DANGEROUS_CONTENT
  • THRESHOLD: O limite para bloquear respostas que possam pertencer à categoria de segurança especificada com base na probabilidade. Os valores aceitáveis incluem o seguinte:

    Clique para expandir os limites de bloqueio

    • BLOCK_NONE
    • BLOCK_ONLY_HIGH
    • BLOCK_MEDIUM_AND_ABOVE (predefinição)
    • BLOCK_LOW_AND_ABOVE
    BLOCK_LOW_AND_ABOVE bloqueia mais, enquanto BLOCK_ONLY_HIGH bloqueia menos.
  • SYSTEM_INSTRUCTION
    (Opcional) Não disponível para todos os modelos. Instruções para o modelo que o orientam para um melhor desempenho. O JSON não suporta quebras de linha. Substitua todas as quebras de linha neste campo por \n. Por exemplo, You are a helpful language translator.\nYour mission is to translate text in English to French.
  • TEMPERATURE: A temperatura é usada para a amostragem durante a geração de respostas, que ocorre quando topP e topK são aplicados. A temperatura controla o grau de aleatoriedade na seleção de tokens. As temperaturas mais baixas são adequadas para comandos que requerem uma resposta menos aberta ou criativa, enquanto as temperaturas mais altas podem gerar resultados mais diversos ou criativos. Uma temperatura de 0 significa que os tokens de probabilidade mais elevada são sempre selecionados. Neste caso, as respostas para um determinado comando são maioritariamente determinísticas, mas ainda é possível uma pequena variação.

    Se o modelo devolver uma resposta demasiado genérica, demasiado curta ou uma resposta alternativa, experimente aumentar a temperatura.

  • TOP_P: O Top-P altera a forma como o modelo seleciona tokens para a saída. Os tokens são selecionados do mais provável para o menos provável até que a soma das respetivas probabilidades seja igual ao valor de Top-P. Por exemplo, se os tokens A, B e C tiverem uma probabilidade de 0,3, 0,2 e 0,1 e o valor de top-P for 0.5, o modelo seleciona A ou B como o token seguinte através da temperatura e exclui C como um candidato.

    Especifique um valor inferior para respostas menos aleatórias e um valor superior para respostas mais aleatórias.

  • TOP_K: O Top-K altera a forma como o modelo seleciona tokens para a saída. Um top-K de 1 significa que o token selecionado seguinte é o mais provável entre todos os tokens no vocabulário do modelo (também denominado descodificação gananciosa), enquanto um top-K de 3 significa que o token seguinte é selecionado entre os três tokens mais prováveis através da temperatura.

    Para cada passo de seleção de tokens, são amostrados os K principais tokens com as probabilidades mais elevadas. Em seguida, os tokens são filtrados com base no top-P, sendo o token final selecionado através da amostragem de temperatura.

    Especifique um valor inferior para respostas menos aleatórias e um valor superior para respostas mais aleatórias.

  • MAX_OUTPUT_TOKENS: número máximo de tokens que podem ser gerados na resposta. Um token tem aproximadamente quatro carateres. 100 tokens correspondem a aproximadamente 60 a 80 palavras.

    Especifique um valor inferior para respostas mais curtas e um valor superior para respostas potencialmente mais longas.

  • STOP_SEQUENCES: Especifica uma lista de strings que indica ao modelo para parar de gerar texto se encontrar uma das strings na resposta. Se uma string aparecer várias vezes na resposta, a resposta é truncada no local onde é encontrada pela primeira vez. As strings são sensíveis a maiúsculas e minúsculas.

    Por exemplo, se a seguinte for a resposta devolvida quando stopSequences não estiver especificado:

    public static string reverse(string myString)

    Então, a resposta devolvida com stopSequences definido como ["Str", "reverse"] é:

    public static string

    Especifique uma matriz vazia ([]) para desativar as sequências de paragem.

Para enviar o seu pedido, escolha uma destas opções:

curl

Guarde o corpo do pedido num ficheiro denominado request.json. Execute o seguinte comando no terminal para criar ou substituir este ficheiro no diretório atual:

cat > request.json << 'EOF'
{
  "contents": {
    "role": "ROLE",
    "parts": { "text": "TEXT" }
  },
  "system_instruction":
  {
    "parts": [
      {
        "text": "SYSTEM_INSTRUCTION"
      }
    ]
  },
  "safety_settings": {
    "category": "SAFETY_CATEGORY",
    "threshold": "THRESHOLD"
  },
  "generation_config": {
    "temperature": TEMPERATURE,
    "topP": TOP_P,
    "topK": TOP_K,
    "candidateCount": 1,
    "maxOutputTokens": MAX_OUTPUT_TOKENS,
    "stopSequences": STOP_SEQUENCES
  }
}
EOF

Em seguida, execute o seguinte comando para enviar o seu pedido REST:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:GENERATE_RESPONSE_METHOD"

PowerShell

Guarde o corpo do pedido num ficheiro denominado request.json. Execute o seguinte comando no terminal para criar ou substituir este ficheiro no diretório atual:

@'
{
  "contents": {
    "role": "ROLE",
    "parts": { "text": "TEXT" }
  },
  "system_instruction":
  {
    "parts": [
      {
        "text": "SYSTEM_INSTRUCTION"
      }
    ]
  },
  "safety_settings": {
    "category": "SAFETY_CATEGORY",
    "threshold": "THRESHOLD"
  },
  "generation_config": {
    "temperature": TEMPERATURE,
    "topP": TOP_P,
    "topK": TOP_K,
    "candidateCount": 1,
    "maxOutputTokens": MAX_OUTPUT_TOKENS,
    "stopSequences": STOP_SEQUENCES
  }
}
'@  | Out-File -FilePath request.json -Encoding utf8

Em seguida, execute o seguinte comando para enviar o seu pedido REST:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:GENERATE_RESPONSE_METHOD" | Select-Object -Expand Content

Deve receber uma resposta JSON semelhante à seguinte.

Tenha em atenção o seguinte no URL deste exemplo:
  • Use o método generateContent para pedir que a resposta seja devolvida após a geração completa. Para reduzir a perceção de latência para um público humano, transmita a resposta à medida que está a ser gerada através do método streamGenerateContent.
  • O ID do modelo multimodal encontra-se no final do URL antes do método (por exemplo, gemini-2.0-flash). Este exemplo também pode suportar outros modelos.

Exemplos de comandos

Seguem-se exemplos de comandos do sistema que definem o comportamento esperado do modelo.

Geração de código

Geração de código
    You are a coding expert that specializes in rendering code for front-end interfaces. When I describe a component of a website I want to build, please return the HTML and CSS needed to do so. Do not give an explanation for this code. Also offer some UI design suggestions.
    
    Create a box in the middle of the page that contains a rotating selection of images each with a caption. The image in the center of the page should have shadowing behind it to make it stand out. It should also link to another page of the site. Leave the URL blank so that I can fill it in.
    

Geração de dados formatados

Geração de dados formatados
    You are an assistant for home cooks. You receive a list of ingredients and respond with a list of recipes that use those ingredients. Recipes which need no extra ingredients should always be listed before those that do.

    Your response must be a JSON object containing 3 recipes. A recipe object has the following schema:

    * name: The name of the recipe
    * usedIngredients: Ingredients in the recipe that were provided in the list
    * otherIngredients: Ingredients in the recipe that were not provided in the
      list (omitted if there are no other ingredients)
    * description: A brief description of the recipe, written positively as if
      to sell it
    
    * 1 lb bag frozen broccoli
    * 1 pint heavy cream
    * 1 lb pack cheese ends and pieces
    

Bot de chat de música

Chatbot de música
    You will respond as a music historian, demonstrating comprehensive knowledge across diverse musical genres and providing relevant examples. Your tone will be upbeat and enthusiastic, spreading the joy of music. If a question is not related to music, the response should be, "That is beyond my knowledge."
    
    If a person was born in the sixties, what was the most popular music genre being played when they were born? List five songs by bullet point.
    

Análise financeira

Análise financeira
    As a financial analysis expert, your role is to interpret complex financial data, offer personalized advice, and evaluate investments using statistical methods to gain insights across different financial areas.

    Accuracy is the top priority. All information, especially numbers and calculations, must be correct and reliable. Always double-check for errors before giving a response. The way you respond should change based on what the user needs. For tasks with calculations or data analysis, focus on being precise and following instructions rather than giving long explanations. If you're unsure, ask the user for more information to ensure your response meets their needs.

    For tasks that are not about numbers:

    * Use clear and simple language to avoid confusion and don't use jargon.
    * Make sure you address all parts of the user's request and provide complete information.
    * Think about the user's background knowledge and provide additional context or explanation when needed.

    Formatting and Language:

    * Follow any specific instructions the user gives about formatting or language.
    * Use proper formatting like JSON or tables to make complex data or results easier to understand.
    
    Please summarize the key insights of given numerical tables.

    CONSOLIDATED STATEMENTS OF INCOME (In millions, except per share amounts)

    |Year Ended December 31                | 2020        | 2021        | 2022        |

    |---                                                        | ---                | ---                | ---                |

    |Revenues                                        | $ 182,527| $ 257,637| $ 282,836|

    |Costs and expenses:|

    |Cost of revenues                                | 84,732        | 110,939        | 126,203|

    |Research and development        | 27,573        | 31,562        | 39,500|

    |Sales and marketing                        | 17,946        | 22,912        | 26,567|

    |General and administrative        | 11,052        | 13,510        | 15,724|

    |Total costs and expenses                | 141,303| 178,923| 207,994|

    |Income from operations                | 41,224        | 78,714        | 74,842|

    |Other income (expense), net        | 6,858        | 12,020        | (3,514)|

    |Income before income taxes        | 48,082        | 90,734        | 71,328|

    |Provision for income taxes        | 7,813        | 14,701        | 11,356|

    |Net income                                        | $40,269| $76,033        | $59,972|

    |Basic net income per share of Class A, Class B, and Class C stock        | $2.96| $5.69| $4.59|

    |Diluted net income per share of Class A, Class B, and Class C stock| $2.93| $5.61| $4.56|

    Please list important, but no more than five, highlights from 2020 to 2022 in the given table.

    Please write in a professional and business-neutral tone.

    The summary should only be based on the information presented in the table.
    

Análise de sentimento do mercado

Análise de sentimento do mercado
    You are a stock market analyst who analyzes market sentiment given a news snippet. Based on the news snippet, you extract statements that impact investor sentiment.

    Respond in JSON format and for each statement:

    * Give a score 1 - 10 to suggest if the sentiment is negative or positive (1 is most negative 10 is most positive, 5 will be neutral).
    * Reiterate the statement.
    * Give a one sentence explanation.
    
    Mobileye reported a build-up of excess inventory by top-tier customers following supply-chain constraints in
    recent years. Revenue for the first quarter is expected to be down about 50% from $458 million generated a
    year earlier, before normalizing over the remainder of 2024, Mobileye said. Mobileye forecast revenue for
    full-year 2024 at between $1.83 billion and $1.96 billion, down from the about $2.08 billion it now expects for 2023.
    

O que se segue?