Google Gemini Logo+Learn JavaScript Logo

Gemini AI Web Course

Free  Gemini AI  course in  JavaScript .

Get started with the Google AI JS SDK by watching this free course.

Download project template

1. Course intro

The first video introduces the course, project template, and final result. We will learn how to create a Gemini API key and discuss restricting the API key and keeping it safe.

At the moment, the Gemini API does not work in the EU.

Pre-requisites

Here are the pre-requisites for this course

  • Basic command line experience (git and npm).
  • Beginner to intermediate experience with JavaScript.
  • Familiar with promises (and async/await).
  • for...of (optional).

Check out this JavaScript knowledge map to brush up on JavaScript.

Create an API key

To create an API key, head over to Google's AI studio: aistudio.google.com (does not work in the EU at the moment).

While we use the API key directly in the code in this demo, this is not recommended outside the context of a demo.Keep your API key safe. Do not commit it to your git repository. Avoid using it in client-side code.

Restricting your API Key

After you create your API Key, we recommend that you click on the arrow next to its name to add restrictions. This is done in the Google Cloud Console.

You can specify restrictions based on IP address, referral header, or restrictions specific to an Android or iOS app.

Create separate API keys for different environments. Only the local API key should be allowed to work on localhost.

Set up the demo project

To set up the demo project, click the download button at the top of this page. Then, extract the zip file and open it in your terminal.

Once you're inside the project, run the following commands to install the node dependencies and run the local dev server:

npm install
npm run dev

2. Basic prompt and streaming responses

The second video shows how to send a basic prompt to the Gemini API and to use streams if we expect longer responses.

Install the Gemini AI JS SDK

Start by installing the Gemini AI JS SDK in your project:

npm install @google/generative-ai

Check out the other available SDKs on ai.google.dev/tutorials

Import and instantiate

Then, import the GoogleGenerativeAI class into your code and instantiate it:

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

const genAi = new GoogleGenerativeAI(YOUR_API_KEY_HERE);

Review the api key safety best practices discussed in the first video.

Afterwards, you can get the generative model:

const model = genAi.getGenerativeModel({ model: "gemini-pro" });

gemini-pro is an alias for gemini-1.0-pro.

Check out the list of all models.

Basic request

You're now ready to send a basic request to the Gemini API:

const result = await model.generateContent("How do you bake a cake?");
const answer = result.response.text();
console.log(answer);

Streaming responses

Streaming responses come in handy when you expect longer responses as you will be able to render parts of the response as they are being received.

const result = await model.generateContentStream("How do you bake a cake?");
for await (const chunk of result.stream) {
  console.log(chunk.text());
}

You can also progressively save the response in a variable:

const result = await model.generateContentStream("How do you bake a cake?");
let response = "";
for await (const chunk of result.stream) {
  response += chunk.text();
  console.log(response);
}

3. Implement predictive support functionality

In the final video, we create and test our prompt and hook it up to our app to implement the predictive support functionality.

Write and test the prompt in AI Studio

Visit aistudio.google.com to write and test the prompt. You can find the FAQs in the prompt.js file.

You can select a piece of text and then click on the {{ }} Test input button in AI Studio to make this an input. You will then be able to test your prompt with different inputs. That's a very neat feature!

Make sure to copy your prompt from AI Studio and paste it in prompt.js when you're done.

Then, replace the two test inputs with the following:

const h1 = document.querySelector("h1")?.textContent;
const currentPage = window.location.pathname;

You can now interpolate these two variables into the prompt.

Interpolating content into your prompt opens up the possibility of prompt injection. Gemini has built-in security features against that, but make sure you test your prompt with various scenarios. If possible, it's best to sanitize content before you interpolate it. For example, you can limit h1's to a specific length and make sure the pathname refers to an actual url on your site.

Implementing predictive support

Now that we have finalized the prompt, we can use it in the main.js by calling the getPrompt() function. This function was already imported at the top of the file.

Also, make sure to move your code into the event listener of the helpButton.

helpButton.addEventListener("click", async () => {
helpBody.textContent = "Loading...";
  const result = await model.generateContent(getPrompt());
  helpBody.textContent = result.response.text();
});

Congratulations! You now have just implemented predictive support functionality in your app.


This course was developed by Jad Joubran – author of Learn JavaScript.

With thanks to Maud Nalpas for reviewing the content of this course.

Learn JavaScript LogoPowered by Learn JavaScript