Skip to content

Commit

Permalink
Add more samples in standardized format (#199)
Browse files Browse the repository at this point in the history
  • Loading branch information
hsubox76 authored Jul 8, 2024
1 parent 05b8631 commit 41389e8
Show file tree
Hide file tree
Showing 8 changed files with 337 additions and 180 deletions.
16 changes: 14 additions & 2 deletions samples/node/README.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
# Google Generative AI Sample for Node.js (Javascript)

This sample demonstrates how to use state-of-the-art
These samples demonstrate how to use state-of-the-art
generative AI models (like Gemini) to build AI-powered features and applications.

To try out this sample, you'll need Node.js v18+.
To try out these samples, you'll need Node.js v18+.

## Requirements

Expand All @@ -13,6 +13,18 @@ It’s strongly recommended that you do not check an API key into your version c

This sample assumes that you're providing an `API_KEY` environment variable.

## Instructions

Each of these sample files can be run in Node.js from the command line, for
example:

```
node function_calling.js
```

Some of these files run multiple example cases sequentially, and you may want
to comment out cases you do not want to run.

## Documentation

- [Quickstart: Get started with the Gemini API in Node.js applications](https://ai.google.dev/tutorials/node_quickstart)
110 changes: 0 additions & 110 deletions samples/node/advanced-function-calling.js

This file was deleted.

54 changes: 0 additions & 54 deletions samples/node/advanced-text-and-images.js

This file was deleted.

81 changes: 81 additions & 0 deletions samples/node/controlled_generation.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
/**
* @license
* Copyright 2024 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.
*/

import {
FunctionDeclarationSchemaType,
GoogleGenerativeAI,
} from "@google/generative-ai";

async function jsonControlledGeneration() {
// [START json_controlled_generation]
const genAI = new GoogleGenerativeAI(process.env.API_KEY);

const schema = {
description: "List of recipes",
type: FunctionDeclarationSchemaType.ARRAY,
items: {
type: FunctionDeclarationSchemaType.OBJECT,
properties: {
recipeName: {
type: FunctionDeclarationSchemaType.STRING,
description: "Name of the recipe",
nullable: false,
},
},
required: ["recipeName"],
},
};

const model = genAI.getGenerativeModel({
model: "gemini-1.5-pro",
generationConfig: {
responseMimeType: "application/json",
responseSchema: schema,
},
});

const result = await model.generateContent(
"List a few popular cookie recipes.",
);
console.log(result.response.text());
// [END json_controlled_generation]
}

async function jsonNoSchema() {
// [START json_no_schema]
const genAI = new GoogleGenerativeAI(process.env.API_KEY);

const model = genAI.getGenerativeModel({
model: "gemini-1.5-flash",
});

const prompt = `List a few popular cookie recipes using this JSON schema:
Recipe = {'recipeName': string}
Return: Array<Recipe>`;

const result = await model.generateContent(prompt);
console.log(result.response.text());
// [END json_no_schema]
}

async function run() {
await jsonControlledGeneration();
await jsonNoSchema();
}

run();
96 changes: 96 additions & 0 deletions samples/node/function_calling.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
/**
* @license
* Copyright 2024 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.
*/

import { GoogleGenerativeAI } from "@google/generative-ai";

async function functionCalling() {
// [START function_calling]
async function setLightValues(brightness, colorTemperature) {
// This mock API returns the requested lighting values
return {
brightness,
colorTemperature,
};
}

const controlLightFunctionDeclaration = {
name: "controlLight",
parameters: {
type: "OBJECT",
description: "Set the brightness and color temperature of a room light.",
properties: {
brightness: {
type: "NUMBER",
description:
"Light level from 0 to 100. Zero is off and 100 is full brightness.",
},
colorTemperature: {
type: "STRING",
description:
"Color temperature of the light fixture which can be `daylight`, `cool` or `warm`.",
},
},
required: ["brightness", "colorTemperature"],
},
};

// Executable function code. Put it in a map keyed by the function name
// so that you can call it once you get the name string from the model.
const functions = {
controlLight: ({ brightness, colorTemperature }) => {
return setLightValues(brightness, colorTemperature);
},
};

const genAI = new GoogleGenerativeAI(process.env.API_KEY);
const model = genAI.getGenerativeModel({
model: "gemini-1.5-flash",
tools: { functionDeclarations: [controlLightFunctionDeclaration] },
});
const chat = model.startChat();
const prompt = "Dim the lights so the room feels cozy and warm.";

// Send the message to the model.
const result = await chat.sendMessage(prompt);

// For simplicity, this uses the first function call found.
const call = result.response.functionCalls()[0];

if (call) {
// Call the executable function named in the function call
// with the arguments specified in the function call and
// let it call the hypothetical API.
const apiResponse = await functions[call.name](call.args);

// Send the API response back to the model so it can generate
// a text response that can be displayed to the user.
const result2 = await chat.sendMessage([
{
functionResponse: {
name: "controlLight",
response: apiResponse,
},
},
]);

// Log the text response.
console.log(result2.response.text());
}
// [END function_calling]
}

functionCalling();
Loading

0 comments on commit 41389e8

Please sign in to comment.