/04. Integrating the GenAI SDK

    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
    Console

    Click "Run" to execute your code...

    🍪 We Value Your Privacy

    We use cookies to enhance your browsing experience, serve personalized ads or content, and analyze our traffic. By clicking "Accept All", you consent to our use of cookies according to our Privacy Policy.

    Learn More