البدء السريع لواجهة برمجة تطبيقات Gemini

يوضّح لك هذا الدليل السريع كيفية تثبيت المكتبات وإرسال طلبك الأول إلى Gemini API.

قبل البدء

يجب أن يكون لديك مفتاح Gemini API. إذا لم يكن لديك حساب، يمكنك الحصول عليه مجانًا في Google AI Studio.

تثبيت حزمة تطوير البرامج (SDK) من Google GenAI

Python

باستخدام Python 3.9 أو إصدار أحدث، ثبِّت الحزمة google-genai باستخدام أمر pip التالي:

pip install -q -U google-genai

JavaScript

باستخدام Node.js الإصدار 18 أو إصدار أحدث، ثبِّت حزمة تطوير البرامج (SDK) من Google للذكاء الاصطناعي التوليدي لنظامَي TypeScript وJavaScript باستخدام أمر npm التالي:

npm install @google/genai

انتقال

ثبِّت google.golang.org/genai في دليل الوحدة باستخدام أمر go get:

go get google.golang.org/genai

Java

إذا كنت تستخدم Maven، يمكنك تثبيت google-genai من خلال إضافة ما يلي إلى الاعتمادات:

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

برمجة تطبيقات

  1. لإنشاء مشروع جديد في "برمجة تطبيقات Google"، انتقِل إلى script.new.
  2. انقر على مشروع بلا عنوان.
  3. أعِد تسمية مشروع Apps Script AI Studio وانقر على إعادة التسمية.
  4. ضبط مفتاح واجهة برمجة التطبيقات
    1. على يمين الصفحة، انقر على إعدادات المشروع رمز إعدادات المشروع.
    2. ضمن خصائص النص البرمجي، انقر على إضافة خاصية للنص البرمجي.
    3. في حقل السمة، أدخِل اسم المفتاح: GEMINI_API_KEY.
    4. في حقل القيمة، أدخِل قيمة مفتاح واجهة برمجة التطبيقات.
    5. انقر على حفظ مواقع النص البرمجي.
  5. استبدِل محتوى ملف Code.gs بالرمز التالي:

تقديم طلبك الأول

إليك مثال يستخدم طريقة generateContent لإرسال طلب إلى Gemini API باستخدام نموذج Gemini 2.5 Flash.

إذا ضبطت مفتاح واجهة برمجة التطبيقات كمتغيّر بيئة GEMINI_API_KEY، سيتم استخدامه تلقائيًا من قِبل العميل عند استخدام مكتبات Gemini 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();

انتقال

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());
  }
}

برمجة تطبيقات

// 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 الذي يتميّز بتفعيل ميزة "التفكير" تلقائيًا لتحسين جودة الردود. يُرجى العِلم أنّ ذلك قد يؤدي إلى زيادة وقت الاستجابة واستخدام الرموز المميزة. إذا كنت تعطي الأولوية للسرعة أو تريد تقليل التكاليف، يمكنك إيقاف هذه الميزة من خلال ضبط ميزانية التفكير على صفر، كما هو موضّح في الأمثلة أدناه. لمزيد من التفاصيل، يُرجى الاطّلاع على دليل التفكير.

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();

انتقال

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
      }
    }
  }'

برمجة تطبيقات

// 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);
}

الخطوات التالية

بعد إرسال طلبك الأول إلى واجهة برمجة التطبيقات، يمكنك الاطّلاع على الأدلة التالية التي توضّح كيفية عمل Gemini: