การเริ่มต้นใช้งาน Gemini API อย่างรวดเร็ว

การเริ่มต้นอย่างรวดเร็วนี้แสดงวิธีติดตั้งไลบรารีของเราและส่งคำขอ Gemini API แรก

ก่อนเริ่มต้น

คุณต้องมีคีย์ Gemini API หากยังไม่มี คุณสามารถรับได้ฟรีใน Google AI Studio

ติดตั้ง Google GenAI SDK

Python

หากใช้ Python 3.9 ขึ้นไป ให้ติดตั้งแพ็กเกจ google-genai โดยใช้คำสั่ง pip ต่อไปนี้

pip install -q -U google-genai

JavaScript

หากใช้ Node.js v18 ขึ้นไป ให้ ติดตั้ง Google Gen AI SDK สำหรับ TypeScript และ JavaScript โดยใช้คำสั่ง npm ต่อไปนี้

npm install @google/genai

Go

ติดตั้ง google.golang.org/genai ใน ไดเรกทอรีโมดูลโดยใช้คำสั่ง go get ดังนี้

go get google.golang.org/genai

Java

หากใช้ Maven คุณจะติดตั้ง google-genai ได้โดยเพิ่มข้อมูลต่อไปนี้ลงในทรัพยากร Dependency

<dependencies>
  <dependency>
    <groupId>com.google.genai</groupId>
    <artifactId>google-genai</artifactId>
    <version>1.0.0</version>
  </dependency>
</dependencies>

Apps Script

  1. หากต้องการสร้างโปรเจ็กต์ Apps Script ใหม่ ให้ไปที่ script.new
  2. คลิกโปรเจ็กต์ที่ไม่มีชื่อ
  3. เปลี่ยนชื่อโปรเจ็กต์ Apps Script เป็น AI Studio แล้วคลิกเปลี่ยนชื่อ
  4. ตั้งค่าคีย์ API
    1. คลิกการตั้งค่าโปรเจ็กต์ ไอคอนสำหรับการตั้งค่าโปรเจ็กต์ ทางด้านซ้าย
    2. ในส่วนพร็อพเพอร์ตี้ของสคริปต์ ให้คลิกเพิ่มพร็อพเพอร์ตี้ของสคริปต์
    3. สำหรับ Property ให้ป้อนชื่อคีย์: GEMINI_API_KEY
    4. สําหรับค่า ให้ป้อนค่าสําหรับคีย์ API
    5. คลิกบันทึกพร็อพเพอร์ตี้ของสคริปต์
  5. แทนที่เนื้อหาไฟล์ Code.gs ด้วยโค้ดต่อไปนี้

ส่งคำขอแรก

ตัวอย่างต่อไปนี้ใช้วิธี generateContent เพื่อส่งคำขอไปยัง Gemini API โดยใช้โมเดล Gemini 2.5 Flash

หากคุณตั้งค่าคีย์ API เป็นตัวแปรสภาพแวดล้อม GEMINI_API_KEY ไคลเอ็นต์จะเลือกคีย์นั้นโดยอัตโนมัติเมื่อใช้ไลบรารี Gemini API มิฉะนั้นคุณจะต้องส่งคีย์ API เป็น อาร์กิวเมนต์เมื่อเริ่มต้นไคลเอ็นต์

โปรดทราบว่าตัวอย่างโค้ดทั้งหมดในเอกสาร Gemini API จะถือว่าคุณได้ตั้งค่า ตัวแปรสภาพแวดล้อม GEMINI_API_KEY แล้ว

Python

from google import genai

# The client gets the API key from the environment variable `GEMINI_API_KEY`.
client = genai.Client()

response = client.models.generate_content(
    model="gemini-2.5-flash", contents="Explain how AI works in a few words"
)
print(response.text)

JavaScript

import { GoogleGenAI } from "@google/genai";

// The client gets the API key from the environment variable `GEMINI_API_KEY`.
const ai = new GoogleGenAI({});

async function main() {
  const response = await ai.models.generateContent({
    model: "gemini-2.5-flash",
    contents: "Explain how AI works in a few words",
  });
  console.log(response.text);
}

main();

Go

package main

import (
    "context"
    "fmt"
    "log"
    "google.golang.org/genai"
)

func main() {
    ctx := context.Background()
    // The client gets the API key from the environment variable `GEMINI_API_KEY`.
    client, err := genai.NewClient(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }

    result, err := client.Models.GenerateContent(
        ctx,
        "gemini-2.5-flash",
        genai.Text("Explain how AI works in a few words"),
        nil,
    )
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(result.Text())
}

Java

package com.example;

import com.google.genai.Client;
import com.google.genai.types.GenerateContentResponse;

public class GenerateTextFromTextInput {
  public static void main(String[] args) {
    // The client gets the API key from the environment variable `GEMINI_API_KEY`.
    Client client = new Client();

    GenerateContentResponse response =
        client.models.generateContent(
            "gemini-2.5-flash",
            "Explain how AI works in a few words",
            null);

    System.out.println(response.text());
  }
}

Apps Script

// See https://developers.google.com/apps-script/guides/properties
// for instructions on how to set the API key.
const apiKey = PropertiesService.getScriptProperties().getProperty('GEMINI_API_KEY');
function main() {
  const payload = {
    contents: [
      {
        parts: [
          { text: 'Explain how AI works in a few words' },
        ],
      },
    ],
  };

  const url = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent';
  const options = {
    method: 'POST',
    contentType: 'application/json',
    headers: {
      'x-goog-api-key': apiKey,
    },
    payload: JSON.stringify(payload)
  };

  const response = UrlFetchApp.fetch(url, options);
  const data = JSON.parse(response);
  const content = data['candidates'][0]['content']['parts'][0]['text'];
  console.log(content);
}

REST

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H 'Content-Type: application/json' \
  -X POST \
  -d '{
    "contents": [
      {
        "parts": [
          {
            "text": "Explain how AI works in a few words"
          }
        ]
      }
    ]
  }'

"การคิด" จะเปิดอยู่โดยค่าเริ่มต้นในตัวอย่างโค้ดหลายรายการ

ตัวอย่างโค้ดหลายรายการในเว็บไซต์นี้ใช้โมเดล Gemini 2.5 Flash ซึ่งเปิดใช้ฟีเจอร์"การคิด" โดยค่าเริ่มต้นเพื่อเพิ่มคุณภาพของคำตอบ โปรดทราบว่าการดำเนินการนี้อาจเพิ่มเวลาในการตอบกลับและการใช้โทเค็น หากต้องการให้ความสำคัญกับความเร็วหรือต้องการลดต้นทุน คุณสามารถปิดใช้ฟีเจอร์นี้ได้โดยตั้งงบประมาณการคิดเป็น 0 ดังที่แสดงในตัวอย่างด้านล่าง ดูรายละเอียดเพิ่มเติมได้ที่คู่มือการคิด

Python

from google import genai
from google.genai import types

client = genai.Client()

response = client.models.generate_content(
    model="gemini-2.5-flash",
    contents="Explain how AI works in a few words",
    config=types.GenerateContentConfig(
        thinking_config=types.ThinkingConfig(thinking_budget=0) # Disables thinking
    ),
)
print(response.text)

JavaScript

import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({});

async function main() {
  const response = await ai.models.generateContent({
    model: "gemini-2.5-flash",
    contents: "Explain how AI works in a few words",
    config: {
      thinkingConfig: {
        thinkingBudget: 0, // Disables thinking
      },
    }
  });
  console.log(response.text);
}

await main();

Go

package main

import (
  "context"
  "fmt"
  "os"
  "google.golang.org/genai"
)

func main() {

  ctx := context.Background()
  client, err := genai.NewClient(ctx, nil)
  if err != nil {
      log.Fatal(err)
  }

  result, _ := client.Models.GenerateContent(
      ctx,
      "gemini-2.5-flash",
      genai.Text("Explain how AI works in a few words"),
      &genai.GenerateContentConfig{
        ThinkingConfig: &genai.ThinkingConfig{
            ThinkingBudget: int32(0), // Disables thinking
        },
      }
  )

  fmt.Println(result.Text())
}

REST

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H 'Content-Type: application/json' \
  -X POST \
  -d '{
    "contents": [
      {
        "parts": [
          {
            "text": "Explain how AI works in a few words"
          }
        ]
      }
    ]
    "generationConfig": {
      "thinkingConfig": {
        "thinkingBudget": 0
      }
    }
  }'

Apps Script

// See https://developers.google.com/apps-script/guides/properties
// for instructions on how to set the API key.
const apiKey = PropertiesService.getScriptProperties().getProperty('GEMINI_API_KEY');

function main() {
  const payload = {
    contents: [
      {
        parts: [
          { text: 'Explain how AI works in a few words' },
        ],
      },
    ],
  };

  const url = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent';
  const options = {
    method: 'POST',
    contentType: 'application/json',
    headers: {
      'x-goog-api-key': apiKey,
    },
    payload: JSON.stringify(payload)
  };

  const response = UrlFetchApp.fetch(url, options);
  const data = JSON.parse(response);
  const content = data['candidates'][0]['content']['parts'][0]['text'];
  console.log(content);
}

ขั้นตอนถัดไป

ตอนนี้คุณได้ส่งคำขอ API แรกแล้ว คุณอาจต้องการดูคำแนะนำต่อไปนี้ที่แสดงการทำงานของ Gemini