Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
194 changes: 194 additions & 0 deletions quickstarts-js/JSON_mode.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,194 @@
/*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/


/* Markdown (render)
# Gemini API: JSON Mode Quickstart


The Gemini API can be used to generate a JSON output if you set the schema that you would like to use.

Two methods are available. You can either set the desired output in the prompt or supply a schema to the model separately.


## Setup
### Install SDK and set-up the client
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two level 3 titles without anything in between


### API Key Configuration

To ensure security, avoid hardcoding the API key in frontend code. Instead, set it as an environment variable on the server or local machine.

When using the Gemini API client libraries, the key will be automatically detected if set as either `GEMINI_API_KEY` or `GOOGLE_API_KEY`. If both are set, `GOOGLE_API_KEY` takes precedence.

For instructions on setting environment variables across different operating systems, refer to the official documentation: [Set API Key as Environment Variable](https://ai.google.dev/gemini-api/docs/api-key#set-api-env-var)

In code, the key can then be accessed as:

```js
ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
```
*/

// [CODE STARTS]
module = await import("https://esm.sh/@google/[email protected]");
GoogleGenAI = module.GoogleGenAI;
ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });

MODEL_ID = "gemini-2.5-flash" // ["gemini-2.5-flash-lite-preview-06-17", "gemini-2.5-flash", "gemini-2.5-pro"]
// [CODE ENDS]

/* Markdown (render)
## Set your constrained output in the prompt
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think you should first explain what Json mode is.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Check how we do it in the documentation, but µI think we should explain why you would need to use json mode (like an example), and then how it works.


For this first example just describe the schema you want back in the prompt:

*/

// [CODE STARTS]
prompt = `
List a few popular cookie recipes using this JSON schema:

Recipe = {'recipe_name': str}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think you should also explain where the format comes from since it's a python thing if I'm not mistaken.

Return: list[Recipe]
`
// [CODE ENDS]

/* Markdown (render)
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](./Get_started_thinking.ipynb) for more details and in particular learn how to switch the thiking off).
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wrong link (point to the python cookbook for now as it will be easier to find them all and fix them)


Then activate JSON mode by specifying `respose_mime_type` in the `config` parameter:
*/

// [CODE STARTS]
rawResponse = await ai.models.generateContent({
model: MODEL_ID,
contents: prompt,
config: {
responseMimeType: 'application/json',
},
});

console.log("```\n",rawResponse.text,"\n```")
// [CODE ENDS]

/* Output Sample

```
[
{
"recipe_name": "Chocolate Chip Cookies"
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think there's an encoding error here.

},
{
"recipe_name": "Oatmeal Raisin Cookies"
},
{
"recipe_name": "Peanut Butter Cookies"
},
{
"recipe_name": "Sugar Cookies"
}
]
```

*/

/* Markdown (render)
## Supply the schema to the model directly

The newest models (1.5 and beyond) allow you to pass a schema object (or a python type equivalent) directly and the output will strictly follow that schema.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we can drop the "newest models" as the older ones are not available anymore.


Following the same example as the previous section, here's that recipe type:
*/

// [CODE STARTS]
recipeSchema = {
type: "object",
properties: {
recipe_name: { type: "string" },
recipe_description: { type: "string" },
recipe_ingredients: {
type: "array",
items: { type: "string" },
},
},
required: ["recipe_name", "recipe_description", "recipe_ingredients"],
};

// [CODE ENDS]

/* Markdown (render)
For this example you want a list of `Recipe` objects, so pass `list[Recipe]` to the `response_schema` field of the `config`.
*/

// [CODE STARTS]
result = 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: {
type: "array",
items: recipeSchema
},
},
});
console.log("```\n",result.text,"\n```");

// [CODE ENDS]

/* Output Sample

```
[
{
"recipe_description": "A crescent of delicate shortbread, infused with the warm embrace of autumnal pear and a whisper of exotic cardamom, culminating in a celestial experience.",
"recipe_ingredients": ["Unsalted butter", "All-purpose flour", "Powdered sugar", "Ripe pears", "Ground cardamom", "Vanilla bean paste"],
"recipe_name": "Celestial Spiced Pear & Cardamom Crescent"
},
{
"recipe_description": "Rich, dark chocolate cookies with a molten espresso ganache heart, dusted with cocoa for an intensely decadent and sophisticated bite.",
"recipe_ingredients": ["Dark cocoa powder", "Unsalted butter", "Granulated sugar", "Eggs", "All-purpose flour", "Espresso powder", "Heavy cream", "Bittersweet chocolate"],
"recipe_name": "Midnight Velvet Espresso Truffle Buttons"
},
{
"recipe_description": "Crisp, golden honey shortbread adorned with delicate crystallized lavender florets, offering a sweet, aromatic, and truly ethereal indulgence.",
"recipe_ingredients": ["Unsalted butter", "All-purpose flour", "Granulated sugar", "Honey", "Culinary lavender", "Egg yolk", "Sea salt"],
"recipe_name": "Lavender Honeycomb Dreams"
}
]
```

*/

/* Markdown (render)
It is the recommended method if you're using a compatible model.
*/

/* Markdown (render)
## Next Steps
### Useful API references:

Check the [structured ouput](https://ai.google.dev/gemini-api/docs/structured-output) documentation or the [`GenerationConfig`](https://ai.google.dev/api/generate-content#generationconfig) API reference for more details

### Related examples

* The constrained output is used in the [Text summarization](https://github.com/google-gemini/cookbook/blob/main/examples/json_capabilities/Text_Summarization.ipynb) example to provide the model a format to summarize a story (genre, characters, etc...)
* The [Object detection](https://github.com/google-gemini/cookbook/blob/main/examples/Object_detection.ipynb) 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](https://github.com/google-gemini/cookbook/blob/main/quickstarts/Enum.ipynb). [Function calling](https://github.com/google-gemini/cookbook/blob/main/quickstarts/Function_calling.ipynb) and [Code execution](https://github.com/google-gemini/cookbook/blob/main/quickstarts/Code_Execution.ipynb) are other ways to enhance your model by either using your own functions or by letting the model write and run them.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe add a link to the quickstart as that's the only one we have at the moment.

*/
3 changes: 2 additions & 1 deletion quickstarts-js/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,5 @@ This is a collection of fun and helpful examples for the Gemini API.
| Cookbook | Description | Features | Open |
| -------- | ----------- | -------- | ---- |
| Get Started | This is our first draft, come back in a few days for the first official JS notebooks | Get started with the JS/TS SDK! | [![Colab](https://storage.googleapis.com/generativeai-downloads/images/Open_in_AIStudio.svg)](https://aistudio.google.com/app/prompts?state=%7B%22ids%22:%5B%221RPwJa-TqASplcgvGTTSIckQ6MWM_IYhg%22%5D,%22action%22:%22open%22,%22userId%22:%22108886437999779306059%22,%22resourceKeys%22:%7B%7D%7D&usp=sharing) |

| JSON Mode | Discover how to use JSON mode. | Using Response Schema to generate structured responses. | [![Colab](https://storage.googleapis.com/generativeai-downloads/images/Open_in_AIStudio.svg)](./) |
<!-- placeholder link -->