All Gemini 1.0 and Gemini 1.5 models are now retired. To avoid service disruption, update to anewer model(for example,gemini-2.5-flash-lite).Learn more.
Get started with server prompt templatesStay organized with collectionsSave and categorize content based on your preferences.
In each request to a model, you send a prompt and optionally schema and
configurations to control the model's response. When usingFirebase AI Logic, you can send all this information directly from your
client code, or you can specify this information server-side usingserver prompt templates.
When using server prompt templates, you store your prompt, schema, and
configurations server-side, and your app passes from the client to the server
only the key (the template ID) referencing a specific template as well as the
required inputs for that template.
When using server prompt templates, you store your prompt and configurations
server-side and only provide a key (the template ID) in your app's codebase.
Here are some benefits of this approach:
Protect against exposing your prompt client-side
Update your prompt and configuration without releasing a new app version
This guide describes how to get started using server prompt templates.
Here are the most important components for an example request to aGeminimodel:
---
model: 'gemini-2.5-flash'
---
{{role "system"}}
All output must be a clearly structured invoice document.
Use a tabular or clearly delineated list format for line items.
{{role "user"}}
Create an example customer invoice for a customer named {{customerName}}.
The top section within the triple-dashes contains the model name as well as
optionally any model configuration, input validation, or schema you want to
send in the request. It's written as key-value pairs and is commonly called
YAMLfrontmatter.
The body of the template contains the prompt. It can also optionally include
system instructions and input values (usingHandlebarssyntax).
Use your template in code
Click yourGemini APIprovider to view provider-specific content
and code on this page.
Here's how to use the template in your code:
Swift
// ...// Initialize the Gemini Developer API backend service// Create a `TemplateGenerativeModel` instanceletmodel=FirebaseAI.firebaseAI(backend:.googleAI()).templateGenerativeModel()letcustomerName="Jane"do{letresponse=tryawaitmodel.generateContent(// Specify your template IDtemplateID:"my-first-template-v1-0-0",// Provide the values for any input variables required by your template.inputs:["customerName":customerName])iflettext=response.text{print("Response Text:\(text)")}}catch{print("An error occurred:\(error)")}print("\n")
Kotlin
// ...// Initialize the Gemini Developer API backend service// Create a `TemplateGenerativeModel` instancevalmodel=Firebase.googleAI.templateGenerativeModel()valcustomerName="Jane"valresponse=model.generateContent(// Specify your template ID"my-first-template-v1-0-0",// Provide the values for any input variables required by your template.mapOf("customerName"tocustomerName))valtext=response.textprintln(text)
Java
// ...// Initialize the Gemini Developer API backend service// Create a `TemplateGenerativeModel` instanceTemplateGenerativeModelgenerativeModel=FirebaseAI.getInstance().templateGenerativeModel();TemplateGenerativeModelFuturesmodel=TemplateGenerativeModelFutures.from(generativeModel);StringcustomerName="Jane";Futureresponse=model.generateContent(// Specify your template ID"my-first-template-v1-0-0",// Provide the values for any input variables required by your template.mapOf("customerName",customerName));addCallback(response,newFutureCallback(){publicvoidonSuccess(GenerateContentResponseresult){System.out.println(result.getText());}publicvoidonFailure(Throwablet){reportError(t);}}executor);
Web
// ...// Initialize the Gemini Developer API backend serviceconstai=getAI(app,{backend:newGoogleAIBackend()});// Create a `TemplateGenerativeModel` instanceconstmodel=getTemplateGenerativeModel(ai);constcustomerName='Jane';constresult=awaitmodel.generateContent(// Specify your template ID'my-first-template-v1-0-0',// Provide the values for any input variables required by your template{customerName:customerName,});constresponse=response.result;consttext=response.text();
Dart
The Flutter plugin will support server prompt templates soon!
Unity
The Unity package will support server prompt templates soon!
Detailed instructions
This section provides detailed instructions for creating, testing, and using
server prompt templates.
Before you begin
If you haven't already,complete thegetting started guide, which
describes how to set up your Firebase project, connect your app to Firebase,
add the SDK, initialize the backend service for your chosenGemini APIprovider, and create aGenerativeModelinstance.
Make sure you have therequired permissionsto create and manage
server prompt templates. By default, all these permissions are included in the
Owner role.
ClickCreate new template, and select a starter template option.
These starter templates provide the format and syntax for some common use
cases. No matter which option you select, though, you can completely
change the template to meet your needs.
This getting started guide assumes you've selected theInput + System Instructionsoption.
Enter the template's identifiers:
Template name: This is a display name for the template (for example,My First Template). It's only visible within Firebase interfaces, like
theFirebaseconsole.
Template ID: This must be a unique ID for the template within your
Firebase project (for example,my-first-template-v1-0-0). You'll reference this
ID in the request from your app.
Template IDs can be max 63 characters and can contain lowercase letters,
numbers, and hyphens.
Modify theConfiguration (frontmatter)section of the template, as
needed.
This section must include at minimum a model name, like this:
---
model: 'gemini-2.5-flash'
---
You can also optionally specify the model's configuration and any input &
output controls, etc. For more details and options, seeTemplate format, syntax, and examples.
Modify thePrompt and (as applicable) system instructionssection of the
template, as needed.
This section must include at minimum the text prompt to send to the model.
(Optional and as applicable)Specify system instructions using the{{role "system"}}syntax, and the text
prompt using the{{role "user"}}syntax.
(Optional)Specify input variables usingHandlebarssyntax (like{{customerName}}). You can provide a
default value in the template, but the value of this input variable is
usually passed in the request.
{{role "system"}}
All output must be a clearly structured invoice document.
Use a tabular or clearly delineated list format for line items.
{{role "user"}}
Create an example customer invoice for a customer named {{customerName}}.
Step 2: Test your template in theFirebaseconsole
TheFirebaseconsole provides a testing experience for your template. This
experience lets you see what will happen when your template is used – both the
format of the request as well as the output of an actual request.
ClickSave templateso that you can test your template.
You can always edit or even delete the template later. The only value you
can't change later is the template ID.
If your prompt uses input variables, include test values in theTest
inputfield. For this example:
{
"customerName": "Jane"
}
If you have multipleGemini APIproviders enabled in your Firebase
project, you can choose which one to use for the test request. If this
option is displayed in the console, select eitherGemini Developer APIorVertex AI Gemini API.
Note that this selection only applies to requests submitted through theFirebaseconsole testing experience. In the actual request from your app,
you specify your chosenGemini APIprovider just like you would for any
request.
Click theCreate formatted test requestbutton.
Review the resultingFormatted test requestin the right-side of the
screen, and iterate on any of your template's fields.
Expand to view example formatted test request
{
"model": "projects/YOUR_PROJECT_ID/models/gemini-2.5-flash",
"contents": [{
"parts": [{
"text": "Create an example customer invoice for a customer named Jane"
}],
"role": "user"
}],
"systemInstruction": {
"parts": [{
"text": "All output must be a clearly structured invoice document.\nUse a tabular or clearly delineated list format for line items."
}]
}
}
When you're satisfied with the formatted test request, click theRun
prompt testbutton.
Review the resultingTest responsein the right-side of the screen, and
iterate on any of your template's fields.
Expand to view example test response
{
"candidates": [{
"content": {
"parts": [{
"text": "```\n--------------------------------------------------------------------------------\n **INVOICE**\n--------------------------------------------------------------------------------\n\n**Creative Solutions Inc.**\n123 Business Lane, Suite 100\nAnytown, USA 12345\nPhone: (555) 123-4567\nEmail: info@creativesolutions.com\n\n**INVOICE NO:** INV-2023-001\n**INVOICE DATE:** October 26, 2023\n**DUE DATE:** November 25, 2023\n\n**BILL TO:**\nJane\n456 Client Street, Apt 2B\nAnytown, USA 12346\nPhone: (555) 987-6543\nEmail: jane@example.com\n\n--------------------------------------------------------------------------------\n**ITEM DESCRIPTION** **QTY** **UNIT PRICE** **AMOUNT**\n--------------------------------------------------------------------------------\nWebsite Design Services 1 $800.00 $800.00\nContent Creation (Blog Posts) 4 $120.00 $480.00\nMonthly Hosting \u0026 Maintenance 1 $50.00 $50.00\nConsultation Fee 2 $75.00 $150.00\n--------------------------------------------------------------------------------\n\n**SUMMARY:**\nSubtotal: $1,480.00\nSales Tax (8%): $118.40\n--------------------------------------------------------------------------------\n**TOTAL DUE:** **$1,598.40**\n--------------------------------------------------------------------------------\n\n**PAYMENT TERMS:**\nPayment is due within 30 days of the invoice date. Please make checks payable to Creative Solutions Inc. For electronic payments, please contact us for details.\n\nThank you for your business!\n```"
}],
"role": "model"
},
"finishReason": "STOP",
"index": 0
}],
"usageMetadata": {
"promptTokenCount": 34,
"candidatesTokenCount": 418,
"totalTokenCount": 890,
"promptTokensDetails": [{
"modality": "TEXT",
"tokenCount": 34
}],
"thoughtsTokenCount": 438
},
"modelVersion": "gemini-2.5-flash",
"responseId": "3w4Vad6yF-y1vdIP_q_zgAw",
"turnToken": "v1:ChczdzRWYWQ2eUYteTF2ZElQX3FfemdBdxIXM3c0VmFkNnlGLXkxdmRJUF9xX3pnQXc"
}
If you're ready to access the template from your app's code,lock the templateby clicking thelocklockicon in the
top-right corner of the template.
ClickCloseto exit the editing experience.
Step 3: Access your template from your code
Click yourGemini APIprovider to view provider-specific content
and code on this page.
A request using a server prompt template looks similar to other requests, with
the following adjustments:
Use atemplateGenerativeModel(ortemplateImagenModel, as needed).
Provide the template ID.
Provide the values of any variable inputs required by your template.
Note that after creating or updating your template, you may need to wait a
couple minutes for the template to propagate across Firebase servers before
accessing it from your code.
Swift
Create atemplateGenerativeModelinstance (ortemplateImagenModel) to use
a template in your request.
// ...// Initialize the Gemini Developer API backend service// Create a `TemplateGenerativeModel` instanceletmodel=FirebaseAI.firebaseAI(backend:.googleAI()).templateGenerativeModel()letcustomerName="Jane"do{letresponse=tryawaitmodel.generateContent(// Specify your template IDtemplateID:"my-first-template-v1-0-0",// Provide the values for any input variables required by your template.inputs:["customerName":customerName])iflettext=response.text{print("Response Text:\(text)")}}catch{print("An error occurred:\(error)")}print("\n")
Kotlin
Create atemplateGenerativeModelinstance (ortemplateImagenModel) to use
a template in your request.
// ...// Initialize the Gemini Developer API backend service// Create a `TemplateGenerativeModel` instancevalmodel=Firebase.googleAI.templateGenerativeModel()valcustomerName="Jane"valresponse=model.generateContent(// Specify your template ID"my-first-template-v1-0-0",// Provide the values for any input variables required by your template.mapOf("customerName"tocustomerName))valtext=response.textprintln(text)
Java
Create atemplateGenerativeModelinstance (ortemplateImagenModel) to use
a template in your request.
// ...// Initialize the Gemini Developer API backend service// Create a `TemplateGenerativeModel` instanceTemplateGenerativeModelgenerativeModel=FirebaseAI.getInstance().templateGenerativeModel();TemplateGenerativeModelFuturesmodel=TemplateGenerativeModelFutures.from(generativeModel);StringcustomerName="Jane";Futureresponse=model.generateContent(// Specify your template ID"my-first-template-v1-0-0",// Provide the values for any input variables required by your template.mapOf("customerName",customerName));addCallback(response,newFutureCallback(){publicvoidonSuccess(GenerateContentResponseresult){System.out.println(result.getText());}publicvoidonFailure(Throwablet){reportError(t);}}executor);
Web
Create atemplateGenerativeModelinstance (ortemplateImagenModel) to use
a template in your request.
// ...// Initialize the Gemini Developer API backend serviceconstai=getAI(app,{backend:newGoogleAIBackend()});// Create a `TemplateGenerativeModel` instanceconstmodel=getTemplateGenerativeModel(ai);constcustomerName='Jane';constresult=awaitmodel.generateContent(// Specify your template ID'my-first-template-v1-0-0',// Provide the values for any input variables required by your template{customerName:customerName,});constresponse=response.result;consttext=response.text();
Dart
The Flutter plugin will support server prompt templates soon!
Unity
The Unity package will support server prompt templates soon!
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2025-11-14 UTC."],[],[]]