You can create your API key using Google AI Studio with a single click.
Remember to treat your API key like a password. Don’t accidentally save it in a notebook or source file you later commit to GitHub. In this notebook we will be storing the API key in a .env file. You can also set it as an environment variable or use a secret manager.
Another option is to set the API key as an environment variable. You can do this in your terminal with the following command:
$ export GEMINI_API_KEY="<YOUR_API_KEY>"
Load the API key
To load the API key from the .env file, we will use the dotenv package. This package loads environment variables from a .env file into process.env.
$ npm install dotenv
Then, we can load the API key in our code:
const dotenv =require("dotenv") astypeofimport("dotenv");dotenv.config({ path:"../.env",});const GEMINI_API_KEY =process.env.GEMINI_API_KEY??"";if (!GEMINI_API_KEY) {thrownewError("GEMINI_API_KEY is not set in the environment variables");}console.log("GEMINI_API_KEY is set in the environment variables");
GEMINI_API_KEY is set in the environment variables
Note
In our particular case the .env is is one directory up from the notebook, hence we need to use ../ to go up one directory. If the .env file is in the same directory as the notebook, you can omit it altogether.
│
├── .env
└── quickstarts
└── JSON_mode.ipynb
Initialize SDK Client
With the new SDK, now you only need to initialize a client with you API key (or OAuth if using Vertex AI). The model is now set in each call.
const google =require("@google/genai") astypeofimport("@google/genai");const ai =new google.GoogleGenAI({ apiKey: GEMINI_API_KEY });
Select a model
Now select the model you want to use in this guide, either by selecting one in the list or writing it down. Keep in mind that some models, like the 2.5 ones are thinking models and thus take slightly more time to respond (cf. thinking notebook for more details and in particular learn how to switch the thiking off).
The newest models (1.5 and beyond) allow you to pass a Schema object directly and the output will strictly follow that schema.
Following the same example as the previous section, here’s that recipe type:
import { Schema, Type } from"@google/genai";const recipeSchema: Schema = { type: Type.OBJECT, description:"A recipe object", properties: { recipeName: { type: Type.STRING, description:"The name of the recipe", }, recipeDescription: { type: Type.STRING, description:"A brief description of the recipe", }, recipeIngredients: { type: Type.ARRAY, description:"A list of ingredients for the recipe", items: { type: Type.STRING, description:"An ingredient for the recipe", }, }, }, required: ["recipeName","recipeDescription","recipeIngredients"],};const listRecipesSchema: Schema = { type: Type.ARRAY, description:"A list of recipes", items: recipeSchema,};const json_schema_response =await ai.models.generateContent({ model: MODEL_ID, contents:"List a few imaginative cookie recipes along with a one-sentence description as if you were a gourmet restaurant and their main ingredients", config: { responseMimeType:"application/json", responseSchema: listRecipesSchema, },});console.log("JSON Schema Response");console.log(JSON.parse(json_schema_response.text!));
JSON Schema Response
[
{
recipeDescription: 'A celestial delight, these cookies shimmer with edible glitter and a hint of lavender, promising an otherworldly experience with every ethereal bite.',
recipeIngredients: [
'All-purpose flour',
'Unsalted butter',
'Granulated sugar',
'Edible glitter',
'Culinary lavender',
'Eggs'
],
recipeName: 'Stardust Serenade Cookies'
},
{
recipeDescription: 'Indulge in the opulent depth of these intensely dark chocolate cookies, encasing a molten truffle heart that melts sensuously on the palate.',
recipeIngredients: [
'Dark cocoa powder',
'Unsalted butter',
'Brown sugar',
'Granulated sugar',
'Chocolate truffles',
'Sea salt'
],
recipeName: 'Velvet Midnight Truffle Cookies'
},
{
recipeDescription: 'These exquisite biscuits offer a harmonious blend of warm spices and tart dried cranberries, evoking a vibrant tapestry of autumnal flavors.',
recipeIngredients: [
'All-purpose flour',
'Unsalted butter',
'Brown sugar',
'Cinnamon',
'Dried cranberries',
'Orange zest'
],
recipeName: 'Spiced Ruby Blossom Biscuits'
}
]
The constrained output is used in the Text summarization example to provide the model a format to summarize a story (genre, characters, etc…)
The Object detection examples are using the JSON constrained output to uniiformize the output of the detection.
Continue your discovery of the Gemini API
JSON is not the only way to constrain the output of the model, you can also use an Enum, Function calling and Code execution are other ways to enhance your model by either using your own functions or by letting the model write and run them.