Gemini API شروع سریع

این راهنمای سریع به شما نشان می‌دهد که چگونه کتابخانه‌های ما را نصب کنید و اولین درخواست خود را انجام دهید، پاسخ‌ها را پخش کنید، مکالمات چند نوبتی بسازید و از ابزارها استفاده کنید.

دو روش برای ارسال درخواست به API جمینی وجود دارد:

  • (توصیه شده) رابط برنامه‌نویسی کاربردی تعاملات (Interactions API) یک رابط کاربری جدید با پشتیبانی داخلی برای استفاده از ابزارهای چند مرحله‌ای، هماهنگ‌سازی و جریان‌های استدلال پیچیده از طریق مراحل اجرای تایپ‌شده است. در آینده، مدل‌های جدید فراتر از خانواده اصلی، همراه با قابلیت‌ها و ابزارهای جدید عامل، منحصراً در رابط برنامه‌نویسی کاربردی تعاملات (Interactions API) راه‌اندازی خواهند شد.
  • generateContent راهی برای تولید یک پاسخ بدون حالت از یک مدل فراهم می‌کند. اگرچه ما استفاده از Interactions API را توصیه می‌کنیم، generateContent کاملاً پشتیبانی می‌شود.

این نسخه از شروع سریع از Interactions API برای ارسال درخواست به Gemini API استفاده می‌کند.

قبل از اینکه شروع کنی

برای استفاده از رابط برنامه‌نویسی Gemini، به یک کلید API نیاز دارید تا درخواست‌های شما را تأیید کند، محدودیت‌های امنیتی را اعمال کند و میزان استفاده از حساب کاربری شما را پیگیری کند.

برای شروع، یکی را به صورت رایگان در AI Studio ایجاد کنید:

یک کلید API جمینی ایجاد کنید

نصب SDK گوگل GenAI

پایتون

با استفاده از پایتون ۳.۹+ ، بسته google-genai را با استفاده از دستور pip زیر نصب کنید:

pip install -q -U google-genai

جاوا اسکریپت

با استفاده از Node.js نسخه ۱۸+ ، کیت توسعه نرم‌افزاری Google Gen AI را برای TypeScript و JavaScript با استفاده از دستور npm زیر نصب کنید:

npm install @google/genai

تولید متن

از متد interactions.create برای تولید یک پاسخ متنی استفاده کنید.

پایتون

from google import genai

client = genai.Client()

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

print(interaction.output_text)

جاوا اسکریپت

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

const ai = new GoogleGenAI({});

async function main() {
  const interaction = await ai.interactions.create({
    model: "gemini-3.5-flash",
    input: "Explain how AI works in a few words",
  });

  console.log(interaction.output_text);
}

main();

استراحت

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

پاسخ‌های استریم

به طور پیش‌فرض، مدل فقط پس از تکمیل کل فرآیند تولید، پاسخ را برمی‌گرداند. برای یک تجربه سریع‌تر و تعاملی‌تر، می‌توانید بخش‌های پاسخ را همزمان با تولید، پخش کنید .

پایتون

stream = client.interactions.create(
    model="gemini-3.5-flash",
    input="Explain how AI works in detail",
    stream=True
)

for event in stream:
    if event.event_type == "step.delta":
        if event.delta.type == "text":
            print(event.delta.text, end="", flush=True)

جاوا اسکریپت

async function main() {
  const stream = await ai.interactions.create({
    model: "gemini-3.5-flash",
    input: "Explain how AI works in detail",
    stream: true,
  });

  for await (const event of stream) {
    if (event.event_type === "step.delta") {
      if (event.delta.type === "text") {
        process.stdout.write(event.delta.text);
      }
    }
  }
}

main();

استراحت

# Use alt=sse for streaming
curl -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions?alt=sse" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H 'Content-Type: application/json' \
  -H "Api-Revision: 2026-05-20" \
  --no-buffer \
  -d '{
    "model": "gemini-3.5-flash",
    "input": "Explain how AI works in detail",
    "stream": true
  }'

مکالمات چند نوبتی

رابط برنامه‌نویسی کاربردی Gemini از ساخت مکالمات چند نوبتی پشتیبانی داخلی دارد. کافیست id برگردانده شده از تعامل قبلی را به عنوان پارامتر previous_interaction_id ارسال کنید تا سرور به طور خودکار تاریخچه مکالمه را مدیریت کند.

پایتون


interaction1 = client.interactions.create(
    model="gemini-3.5-flash",
    input="I have 2 dogs in my house."
)
print("Response 1:", interaction1.output_text)

interaction2 = client.interactions.create(
    model="gemini-3.5-flash",
    input="How many paws are in my house?",
    previous_interaction_id=interaction1.id
)
print("Response 2:", interaction2.output_text)

جاوا اسکریپت

async function main() {
  const interaction1 = await ai.interactions.create({
    model: "gemini-3-flash-preview",
    input: "I have 2 dogs in my house.",
  });
  console.log("Response 1:", interaction1.output_text);

  const interaction2 = await ai.interactions.create({
    model: "gemini-3-flash-preview",
    input: "How many paws are in my house?",
    previous_interaction_id: interaction1.id,
  });
  console.log("Response 2:", interaction2.output_text);
}

main();

استراحت

# Turn 1: Start the conversation
RESPONSE1=$(curl -s -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "Api-Revision: 2026-05-20" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{
    "model": "gemini-3-flash-preview",
    "input": "I have 2 dogs in my house."
  }')

# Extract the interaction ID
INTERACTION_ID=$(echo "$RESPONSE1" | jq -r '.id')

# Turn 2: Continue the conversation
curl -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "Api-Revision: 2026-05-20" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H 'Content-Type: application/json' \
  -d "{
    \"model\": \"gemini-3-flash-preview\",
    \"input\": \"How many paws are in my house?\",
    \"previous_interaction_id\": \"$INTERACTION_ID\"
  }"

از ابزارها استفاده کنید

با پایه‌گذاری پاسخ‌ها با جستجوی گوگل برای دسترسی به محتوای وب در لحظه، قابلیت‌های مدل را گسترش دهید. مدل به‌طور خودکار تصمیم می‌گیرد چه زمانی جستجو کند، پرس‌وجوها را اجرا می‌کند و پاسخ را با استنادها ترکیب می‌کند.

مثال زیر نحوه فعال کردن جستجوی گوگل را نشان می‌دهد:

پایتون

interaction = client.interactions.create(
    model="gemini-3-flash-preview",
    input="Who won the euro 2024?",
    tools=[{"type": "google_search"}]
)

print(interaction.output_text)

for step in interaction.steps:
    if step.type == "model_output":
        for content_block in step.content:
            if content_block.type == "text" and content_block.annotations:
                print("\nCitations:")
                for annotation in content_block.annotations:
                    if annotation.type == "url_citation":
                        print(f"  - [{annotation.title}]({annotation.url})")

جاوا اسکریپت

async function main() {
  const interaction = await ai.interactions.create({
    model: "gemini-3-flash-preview",
    input: "Who won the euro 2024?",
    tools: [{ type: "google_search" }]
  });

  console.log(interaction.output_text);

  for (const step of interaction.steps) {
    if (step.type === 'model_output') {
      for (const contentBlock of step.content) {
        if (contentBlock.type === 'text' && contentBlock.annotations) {
          console.log("\nCitations:");
          for (const annotation of contentBlock.annotations) {
            if (annotation.type === 'url_citation') {
              console.log(`  - [${annotation.title}](${annotation.url})`);
            }
          }
        }
      }
    }
  }
}

main();

استراحت

curl -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "Api-Revision: 2026-05-20" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-3-flash-preview",
    "input": "Who won the euro 2024?",
    "tools": [{"type": "google_search"}]
  }'

رابط برنامه‌نویسی Gemini همچنین از ابزارهای داخلی دیگری نیز پشتیبانی می‌کند:

  • اجرای کد : به مدل اجازه می‌دهد کد پایتون را برای حل مسائل پیچیده ریاضی بنویسد و اجرا کند.
  • زمینه URL : به شما امکان می‌دهد پاسخ‌ها را در URLهای صفحات وب خاصی که ارائه می‌دهید، قرار دهید.
  • جستجوی فایل : به شما امکان می‌دهد فایل‌ها را آپلود کنید و با استفاده از جستجوی معنایی، پاسخ‌ها را در محتوای آنها قرار دهید.
  • نقشه‌های گوگل : به شما امکان می‌دهد پاسخ‌ها را در داده‌های مکانی قرار دهید و مکان‌ها، مسیرها و نقشه‌ها را جستجو کنید.
  • استفاده از کامپیوتر : به مدل اجازه می‌دهد تا با یک صفحه نمایش مجازی کامپیوتر، صفحه کلید و ماوس برای انجام وظایف تعامل داشته باشد.

فراخوانی توابع سفارشی

از فراخوانی تابع برای اتصال مدل‌ها به ابزارها و APIهای سفارشی خود استفاده کنید. مدل زمان فراخوانی تابع شما را تعیین می‌کند و یک مرحله function_call را به همراه آرگومان‌هایی برای اجرای برنامه شما برمی‌گرداند.

این مثال یک تابع دمای شبیه‌سازی‌شده را تعریف می‌کند و بررسی می‌کند که آیا مدل می‌خواهد آن را فراخوانی کند یا خیر.

پایتون

import json

weather_function = {
    "type": "function",
    "name": "get_current_temperature",
    "description": "Gets the current temperature for a given location.",
    "parameters": {
        "type": "object",
        "properties": {
            "location": {
                "type": "string",
                "description": "The city name, e.g. San Francisco",
            },
        },
        "required": ["location"],
    },
}

interaction = client.interactions.create(
    model="gemini-3-flash-preview",
    input="What's the temperature in London?",
    tools=[weather_function],
)

fc_step = None
for step in interaction.steps:
    if step.type == "function_call":
        fc_step = step
        break

if fc_step:
    print(f"Model requested function: {fc_step.name} with args {fc_step.arguments}")

    mock_result = {"temperature": "15C", "condition": "Cloudy"}

    final_interaction = client.interactions.create(
        model="gemini-3-flash-preview",
        input=[
            {
                "type": "function_result",
                "name": fc_step.name,
                "call_id": fc_step.id,
                "result": [{"type": "text", "text": json.dumps(mock_result)}],
            }
        ],
        tools=[weather_function],
        previous_interaction_id=interaction.id,
    )
    print("Final Response:", final_interaction.output_text)

جاوا اسکریپت

async function main() {
  const weatherFunction = {
    type: 'function',
    name: 'get_current_temperature',
    description: 'Gets the current temperature for a given location.',
    parameters: {
      type: 'object',
      properties: {
        location: {
          type: 'string',
          description: 'The city name, e.g. San Francisco',
        },
      },
      required: ['location'],
    },
  };

  const interaction = await ai.interactions.create({
    model: 'gemini-3-flash-preview',
    input: "What's the temperature in London?",
    tools: [weatherFunction],
  });

  const fcStep = interaction.steps.find(s => s.type === 'function_call');
  if (fcStep) {
    console.log(`Model requested function: ${fcStep.name}`);

    const mockResult = { temperature: "15C", condition: "Cloudy" };

    const finalInteraction = await ai.interactions.create({
      model: 'gemini-3-flash-preview',
      input: [{
        type: 'function_result',
        name: fcStep.name,
        call_id: fcStep.id,
        result: [{ type: 'text', text: JSON.stringify(mockResult) }]
      }],
      tools: [weatherFunction],
      previous_interaction_id: interaction.id,
    });

    console.log("Final Response:", finalInteraction.output_text);
  }
}

main();

استراحت

curl -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "Api-Revision: 2026-05-20" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-3-flash-preview",
    "input": "What'\''s the temperature in London?",
    "tools": [{
      "type": "function",
      "name": "get_current_temperature",
      "description": "Gets the current temperature for a given location.",
      "parameters": {
        "type": "object",
        "properties": {
          "location": {"type": "string", "description": "The city name"}
        },
        "required": ["location"]
      }
    }]
  }'

قدم بعدی چیست؟

حالا که کار با رابط برنامه‌نویسی کاربردی Gemini را شروع کرده‌اید، برای ساخت برنامه‌های پیشرفته‌تر، راهنماهای زیر را بررسی کنید: