使用系統指令

本文將說明如何使用系統指令。如要瞭解系統指示的定義和使用系統指示的最佳做法,請參閱「系統指示簡介」。

系統指令是一組指令,模型會先處理這組指令,再處理提示詞。建議您使用系統指令來調整模型行為,告訴模型應如何回應提示詞。舉例來說,您可以加入角色或人物角色、背景資訊和格式指示:

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.

設定系統指令後,就會套用至整個要求。只要在提示詞中包含指令,就能用於多位使用者和模型的對話回合。雖然系統操作說明與提示內容是分開的,但仍屬於整體提示內容的一部分,因此必須遵守標準資料使用政策。

用途

您可以透過多種方式使用系統指示,包括:

  • 定義人物角色或角色 (例如聊天機器人)
  • 定義輸出格式 (Markdown、YAML 等)
  • 定義輸出樣式和語氣 (例如冗長程度、正式程度和目標閱讀程度)
  • 定義工作目標或規則 (例如傳回程式碼片段,但未提供進一步說明)
  • 為提示提供額外背景資訊 (例如知識門檻)
  • 指定模型應以哪種語言回覆 (有時模型可以以當地語言回覆,即使提示以其他語言撰寫也一樣)。如果您使用非英文語言做為提示,建議您在系統操作說明中加入以下內容:

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

程式碼範例

下列分頁中的程式碼範例示範如何在生成式 AI 應用程式中使用系統指令。

Gen AI SDK for Python

安裝

pip install --upgrade google-genai

詳情請參閱 SDK 參考說明文件

設定環境變數,以便在 Vertex AI 中使用 Gen AI SDK:

# 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 ?

Gen AI SDK for Go

瞭解如何安裝或更新 Gen AI SDK for Go

詳情請參閱 SDK 參考說明文件

設定環境變數,以便在 Vertex AI 中使用 Gen AI SDK:

# 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.0-flash-001"
	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, err := resp.Text()
	if err != nil {
		return fmt.Errorf("failed to convert model response to text: %w", err)
	}
	fmt.Fprintln(w, respText)

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

	return nil
}

Gen AI SDK for Node.js

安裝

npm install @google/genai

詳情請參閱 SDK 參考說明文件

設定環境變數,以便在 Vertex AI 中使用 Gen AI SDK:

# 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 ai = new GoogleGenAI({
    vertexai: true,
    project: projectId,
    location: location,
  });

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

  const response = await ai.models.generateContent({
    model: 'gemini-2.0-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;
}

Gen AI SDK for Java

瞭解如何安裝或更新 Gen AI SDK for Java

詳情請參閱 SDK 參考說明文件

設定環境變數,以便在 Vertex AI 中使用 Gen AI SDK:

# 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 GenerateContentWithSystemInstruction {

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

  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()
        .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, Content.fromParts(
                  Part.fromText("Why is the sky blue?")),
              config);

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

REST

設定環境後,您可以使用 REST 測試文字提示。以下範例會將要求傳送至發布商模型端點。

使用任何要求資料之前,請先替換以下項目:

  • GENERATE_RESPONSE_METHOD:您希望模型產生的回應類型。選擇一種方法,讓模型產生所需的回覆:
    • streamGenerateContent:回應會在產生時串流傳輸,以減少使用者感知的延遲時間。
    • generateContent:回應會在完全產生後傳回。
  • LOCATION:處理要求的區域。可用的選項包括:

    點選展開可用地區的部分清單

    • us-central1
    • us-west4
    • northamerica-northeast1
    • us-east4
    • us-west1
    • asia-northeast3
    • asia-southeast1
    • asia-northeast1
  • PROJECT_ID:您的專案 ID
  • MODEL_ID:您要使用的多模態模型的模型 ID。
  • ROLE:與內容相關聯的對話中角色。即使是單轉使用情境,也必須指定角色。可接受的值包括:
    • USER:指定您傳送的內容。
    • MODEL:指定模型的回覆。
  • TEXT
    在提示中加入的文字操作說明。例如:User input: I like bagels
  • SAFETY_CATEGORY:要設定安全門檻的安全類別。可接受的值包括:

    按一下展開安全性類別

    • HARM_CATEGORY_SEXUALLY_EXPLICIT
    • HARM_CATEGORY_HATE_SPEECH
    • HARM_CATEGORY_HARASSMENT
    • HARM_CATEGORY_DANGEROUS_CONTENT
  • THRESHOLD:根據機率封鎖可能屬於特定安全類別的回應門檻。可接受的值包括:

    點選展開封鎖門檻

    • BLOCK_NONE
    • BLOCK_ONLY_HIGH
    • BLOCK_MEDIUM_AND_ABOVE (預設)
    • BLOCK_LOW_AND_ABOVE
    BLOCK_LOW_AND_ABOVE 會封鎖最多內容,BLOCK_ONLY_HIGH 則會封鎖最少的內容。
  • SYSTEM_INSTRUCTION
    (選用) 並非所有型號都支援。模型的操作說明,可引導模型提升效能。JSON 不支援換行符號。將此欄位中的所有換行符號替換為 \n。例如:You are a helpful language translator.\nYour mission is to translate text in English to French.
  • TEMPERATURE:溫度會在回覆產生期間用於取樣,這會在套用 topPtopK 時發生。溫度參數會決定選取詞元時的隨機程度。如果您想藉由提示生成較不具開放性和創意性的回覆,建議調低溫度參數。另一方面,如果溫度參數較高,則可能產生較多樣化或有創意的結果。如果溫度參數為 0,系統一律會選取可能性最高的詞元。在這種情況下,系統會根據特定提示提供的回覆,但仍可能出現少量變化。

    如果模型的回覆太普通、太短或提供了備用回覆,再試試看調高溫度參數。

  • TOP_P:Top-P 會影響模型選取輸出符記的方式。模型會按照可能性最高到最低的順序選取符記,直到所選符記的可能性總和等於 Top-P 值。舉例來說,假設詞元 A、B 和 C 的可能性分別為 0.3、0.2 和 0.1,而 Top-P 值為 0.5,模型會依據溫度參數選擇 A 或 B 做為下一個詞元,並排除 C 做為候選詞元。

    如要取得較不隨機的回覆,請指定較低的值;如要取得較隨機的回覆,請調高此值。

  • TOP_K:Top-K 會影響模型選取輸出符記的方式。如果「前 K 個」設為 1,代表下一個所選詞元是模型詞彙表的所有詞元中可能性最高者 (也稱為「貪婪解碼」)。如果「前 K 個」設為 3,則代表模型會依據溫度參數,從可能性最高的 3 個詞元中選取下一個詞元。

    在每個符記選取步驟中,模型會對機率最高的「Top-K」符記取樣,接著進一步根據「Top-P」篩選詞元,最後依 temperature 選出最終詞元。

    如要取得較不隨機的回覆,請指定較低的值;如要取得較隨機的回覆,請調高此值。

  • MAX_OUTPUT_TOKENS:回覆內可以生成的符記數量上限。一個符記約為四個字元。100 個符記大約對應 60 到 80 個字詞。

    如要取得較短的回覆,請指定較低的值;如要取得較長的回覆,請調高此值。

  • STOP_SEQUENCES:指定字串清單,如果模型在回應中遇到其中一個字串,就會停止產生文字。如果字串在回應中出現多次,回應會截斷首次遇到的字串。字串須區分大小寫。

    舉例來說,如果未指定 stopSequences,系統會傳回以下回應:

    public static string reverse(string myString)

    如果 stopSequences 設為 ["Str", "reverse"],系統會傳回以下回應:

    public static string

    指定空陣列 ([]) 來停用停止序列。

如要傳送要求,請選擇以下其中一個選項:

curl

將要求主體儲存在名為 request.json 的檔案中。在終端機中執行下列指令,在目前目錄中建立或覆寫此檔案:

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

接著,執行下列指令來傳送 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

將要求主體儲存在名為 request.json 的檔案中。在終端機中執行下列指令,在目前目錄中建立或覆寫此檔案:

@'
{
  "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

接著,執行下列指令來傳送 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

您應該會收到類似以下的 JSON 回應。

請注意,此範例網址中的以下內容:
  • 使用 generateContent 方法,要求在回覆完全產生後傳回。為減少使用者對延遲的感受,請使用 streamGenerateContent 方法,在回覆生成的同時串流回覆內容。
  • 多模態模型 ID 位於網址結尾,位於方法 (例如 gemini-2.0-flash) 之前。這個範例可能也支援其他模型。

提示範例

以下是系統提示的範例,可定義模型的預期行為。

程式碼生成

生成程式碼
    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.
    

格式化資料產生

格式化資料產生
    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
    

音樂聊天機器人

音樂聊天機器人
    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.
    

財務分析

財務分析
    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.
    

市場情緒分析

市場情緒分析
    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.
    

後續步驟

  • 如要查看更多提示範例,請前往提示庫