Exporting prompts from AI Studio to JavaScript and writing NodeJS scripts with the Gemini API

1. Introduction

Google AI Studio is a web-based tool for prototyping and experimenting with prompt engineering and Gemini is our latest LLM which can be selected as your model via Google AI Studio.

In this codelab, you will learn how to take a prompt you've prototyped in Google AI Studio and generate a code snippet from your prototype to be embedded into a command-line JavaScript script.

Prerequisites

  • A basic understanding of JavaScript.
  • Command-line access to a computer with NodeJS and NPM installed.
  • A basic understanding of input and output in data processing.
  • Access to the Google AI Studio tool at: https://makersuite.google.com/

What you'll learn

  • How to export code from Google AI Studio.
  • How to export an API key for Google AI Studio to call the API from code.
  • How to write a basic script for NodeJS that calls the API for Gemini.

2. Setting up a basic prompt in Google AI Studio

We'll start by opening Google AI Studio and creating a basic prompt.

First, navigate to Google AI Studio:

https://makersuite.google.com/

You'll need to sign in with a valid Google account.

After logging in, click the "Create new" button and then select "Freeform prompt":

c81d68bb4746f823.png

You should now see this UI:

892d5d86502dec56.png

Under the heading "Write your prompt", try inputting the following prompt:

Write a tech support email response for this question:

"I can't use my emails and passwords in Chrome."

Google AI Studio will call the Gemini API and formulate a response.

This is a great place to pause in our prompt engineering. Next we'll organize API access for ourselves and get an API token for Google AI Studio so that we can export this prompt into a JavaScript code snippet.

3. Getting API Access via Google AI Studio for coding

In the primary navigation, hover over the key icon ("Get API key") and click it.

f2c303d0e92b2521.png

If you don't have any API keys already created. You can generate a key via this UI:

a1b218c4869c6cba.png

After you've successfully generated a key (or noted you can see a key below) you can test your key using the cURL command at the bottom of the page. This command will use cURL to directly call the API server with a single prompt request "Write a story about a magic backpack" and return the JSON response from the server:

a4fd1fbfb9d5af5b.png

For the above command to work, the local shell variable YOUR_API_KEY will need to be set:

YOUR_API_KEY=<<key goes here>>

And you'll need to add $ in front of YOUR_API_KEY in the cURL command itself.

Your command-line response should be something like this:

{
  "candidates": [
    {
      "output": "Once upon a time, there was a young boy named Jack who lived in a small village. Jack was a kind and hardworking boy, but he was also very poor. One day, Jack was walking through..."
    }
  ]
}

If not, try debugging your access issues using the following documentation:

https://ai.google.dev/tutorials/setup

4. Using the "Get Code" feature

Once you've successfully gained access to the API and your cURL command succeeded, it's time to go back to your prompt and try exporting it as a piece of code.

We'll start by exporting it as another cURL command line prompt. In the top-right corner, click "Get code".

9a2167bb3515acb7.png

You should see a modal appear that looks like this:

d50c268e1ad1d5ce.png

Change to the cURL tab and click "Copy" to copy and paste the code to your command line.

Be sure to enter your API key into the line that sets the API_KEY variable, like so:

API_KEY=<<key goes here>>

And try running this on your command-line.

The response should look something like this:

{
  "candidates": [
    {
      "output": "Dear [Customer Name],\n\nI'm sorry to hear that you're having trouble using your emails and passwords in Chrome. I'd be happy to help you troubleshoot this issue.\n\nHere are a few things ..."
    }
  ]
}

Which means we have success!

Let's now test the JavaScript export feature. This option will give us JavaScript sample code that directly invokes the prompt we've been building in AI Studio.

5. Setting up a basic script and calling the API

Open the "Get code" modal again in Google AI Studio and select the JavaScript tab this time. A sample script will appear again.

333046487c591075.png

Try copying and pasting this code into a script file titled test.js

Now on the command-line, run the following commands.

To install the Google AI Generative Language library:

npm install @google/generative-ai

Your test.js file should look something like this:

const { GoogleGenerativeAI } = require("@google/generative-ai");

async function singleRequest() {
  const genAI = new GoogleGenerativeAI(process.env.API_KEY);
 
  const model = genAI.getGenerativeModel({
    model: "gemini-pro",
  });
  const result = await model.generateContent({
    contents: [
      {
        role: "user",
        parts: [{ text: `Write a tech support email response for this question:

        "I can't use my emails and passwords in Chrome."` }],
      },
    ],
  });
  const response = await result.response;
  console.log(JSON.stringify(response));
}

singleRequest();

This exported code imports the Google Generative AI library and fires a single request via an async function. That request initializes the library using your API key, accessed via your local environment variables using the process package.

After the library is initialized, the code requests a particular model. There are multiple models available in the Gemini API such as ‘gemini-pro' and ‘gemini-pro-vision' at the moment. For the purpose of this codelab, we're not exploring the multimodal image features of Gemini so we only need to request the Gemini Pro model.

Finally, the script calls model.generateContent, which calls the LLM's freeform text prompt API end point and returns a JSON response with the resulting text response and other information.

And now to run our test script:

node test.js

By default, you should receive an error with the error code 3 and the following in the details field of the payload response

details: ‘API key not valid. Please pass a valid API key.'

The issue is that our script needs the API_KEY constant defined.

On line 6 of your script, update the following code to include your API key which we configured earlier in this codelab:

const API_KEY = "YOUR API KEY";

Run the script again:

node test.js

You should see a response that looks something like this:

{
    "candidates": [{
        "content": {
            "parts": [{
                "text": "Subject: Troubleshooting Email and Password Issues in Chrome\n\nDear [Name],\n\nThank you for reaching out regarding the difficulty you're experiencing with using your emails and passwords in Chrome. I apologize for any inconvenience it has caused. Let's work together to resolve this issue promptly.\n\nTo pinpoint the issue accurately, please provide me with the following information:\n\n- Ensure that you provided us with the correct email address associated with your account.\n\n- Verify if the same issue persists when accessing your emails and passwords using a different browser, such as Firefox or Microsoft Edge.\n\n- Can you please confirm that you have checked your keyboard layout to ensure it is configured correctly?\n\n- Have you tried clearing the cache and cookies in your Chrome browser? This can often resolve issues related to login credentials.\n\nTo clear the cache and cookies in Chrome, follow these steps:\n - Open Chrome on your computer.\n - Click the vertical three-dot icon in the top-right corner of the Chrome window.\n - Select \"More tools\" and then \"Clear browsing data.\"\n - In the \"Time range\" drop-down menu, select \"All time.\"\n - Make sure that \"Cookies and other site data\" and \"Cached images and files\" are selected.\n - Click the \"Clear data\" button.\n\nIf the issue persists after completing the suggestions above, please provide us with the following additional information:\n\n- A screenshot of the error message you are encountering would be helpful in understanding the issue better.\n\n- Kindly inform us if you recently made any changes to your computer, such as installing new software or updating your operating system.\n\nOur team is committed to providing you with the best possible support. We appreciate your patience and cooperation as we work to resolve this matter for you.\n\nDon't hesitate to contact us if you have any questions or require further assistance.\n\nBest regards,\n\n[Your Name]\nTechnical Support Representative"
            }]
        },
        "index": 0
    }],
    "promptFeedback": {
        "safetyRatings": [{
            "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
            "probability": "NEGLIGIBLE"
        }, {
            "category": "HARM_CATEGORY_HATE_SPEECH",
            "probability": "NEGLIGIBLE"
        }, {
            "category": "HARM_CATEGORY_HARASSMENT",
            "probability": "NEGLIGIBLE"
        }, {
            "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
            "probability": "NEGLIGIBLE"
        }]
    }
}

The output field contains the LLM's response. The other fields are metadata associated with the response.

6. Reflection

Today you've learned how to use Google AI Studio to prototype a freeform text prompt and export it from Google AI Studio to JavaScript. You've also set up API access to Gemini and integrated your API key into your script and successfully run the script from the command line via both cURL and a NodeJS powered JavaScript stand-alone script.

From here you could export the prompt to Python instead and use the API from Python or expand on your NodeJS project.