From 901527e75dc36ef857c1114912bfd61c4253142b Mon Sep 17 00:00:00 2001 From: Anand Roy <86306690+andycandy@users.noreply.github.com> Date: Tue, 15 Jul 2025 01:51:39 +0530 Subject: [PATCH 1/2] pushing json --- quickstarts-js/JSON_mode.js | 177 ++++++++++++++++++++++++++++++++++++ quickstarts-js/README.md | 3 +- 2 files changed, 179 insertions(+), 1 deletion(-) create mode 100644 quickstarts-js/JSON_mode.js diff --git a/quickstarts-js/JSON_mode.js b/quickstarts-js/JSON_mode.js new file mode 100644 index 000000000..a3c76bac2 --- /dev/null +++ b/quickstarts-js/JSON_mode.js @@ -0,0 +1,177 @@ +/* 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 + +### 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/genai@1.4.0"); +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 + +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} + 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). + +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" + }, + { + "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. + +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. +*/ \ No newline at end of file diff --git a/quickstarts-js/README.md b/quickstarts-js/README.md index e1a5e3167..dbdb6b8ba 100644 --- a/quickstarts-js/README.md +++ b/quickstarts-js/README.md @@ -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)](./) | + From a49558b69228575be4d90cab04da64d2fee61a22 Mon Sep 17 00:00:00 2001 From: Anand Roy <86306690+andycandy@users.noreply.github.com> Date: Tue, 15 Jul 2025 01:58:38 +0530 Subject: [PATCH 2/2] header update --- quickstarts-js/JSON_mode.js | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/quickstarts-js/JSON_mode.js b/quickstarts-js/JSON_mode.js index a3c76bac2..27b5c6783 100644 --- a/quickstarts-js/JSON_mode.js +++ b/quickstarts-js/JSON_mode.js @@ -1,3 +1,20 @@ +/* + * 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