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

คู่มือเริ่มใช้งานฉบับย่อนี้แสดงให้คุณเห็นถึงวิธีติดตั้งไลบรารีของเราและส่งคำขอ API ของ Gemini ครั้งแรกโดยใช้ Interactions API

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

การใช้ Gemini API ต้องใช้คีย์ API ซึ่งคุณสร้างได้ฟรีเพื่อเริ่มต้นใช้งาน

สร้างคีย์ Gemini API

ติดตั้ง 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

ส่งคำขอครั้งแรก

นี่คือตัวอย่างที่ใช้ Interactions API เพื่อส่งคำขอไปยัง Gemini API โดยใช้โมเดล Gemini 3 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()

interaction = client.interactions.create(
    model="gemini-3-flash-preview", 
    input="Explain how AI works in a few words"
)

# Print the model's text response
for step in interaction.steps:
    if step.type == "model_output":
        for content_block in step.content:
            if content_block.type == "text":
                print(content_block.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 interaction = await ai.interactions.create({
    model: "gemini-3-flash-preview",
    input: "Explain how AI works in a few words",
  });

  const modelStep = interaction.steps.find(s => s.type === 'model_output');
  if (modelStep) {
    for (const contentBlock of modelStep.content) {
      if (contentBlock.type === 'text') console.log(contentBlock.text);
    }
  }
}

main();

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{
    "model": "gemini-3-flash-preview",
    "input": "Explain how AI works in a few words"
  }'

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

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