04. Integrating the GenAI SDK
Explanation
Because our sandbox now supports ES Modules and asynchronous operations, you can import real production libraries directly from CDNs like `esm.sh`.
This allows us to write authentic JavaScript code exactly as you would in a real Node.js or browser environment.
The `@google/genai` SDK abstracts away the complex HTTP requests, giving you a clean, promise-based interface to interact with Gemini.
Example
import { GoogleGenAI } from 'https://esm.sh/@google/genai';
const ai = new GoogleGenAI({ apiKey: '...'});
const res = await ai.models.generateContent({
model: 'gemini-2.5-flash',
contents: 'Hello!'
});
console.log(res.text);Exercise Task
We will use the official Google GenAI SDK to interact directly with an LLM from our browser sandbox.
**Step 1.** Import `GoogleGenAI` from `https://esm.sh/@google/genai`.
**Step 2.** Initialize the client: `const ai = new GoogleGenAI({ apiKey: 'YOUR_GEMINI_API_KEY' })`.
**Step 3.** Use `ai.models.generateContent` with the model `gemini-2.5-flash` to ask: "Explain APIs to a 5-year-old in one sentence."
**Step 4.** Log `response.text` to the console.
script.js
1
2
3
4
5
6
7
8
9
10
// 1. Import GoogleGenAI
// 2. Initialize the client
const apiKey =
'PASTE_YOUR_API_KEY_HERE'; // DO NOT
share this code publicly with your real
key!
// 3. Generate Content (Remember to use
'await')
async function run() {
}
Console
Click "Run" to execute your code...