این آموزش سریع به شما نشان میدهد که چگونه کتابخانههای ما را نصب کنید و اولین درخواست خود را ایجاد کنید، پاسخها را پخش کنید، مکالمات چند نوبتی بسازید و از ابزارها با استفاده از روش استاندارد generateContent استفاده کنید.
قبل از اینکه شروع کنی
برای استفاده از رابط برنامهنویسی Gemini، به یک کلید API نیاز دارید تا درخواستهایتان را تأیید کنید، محدودیتهای امنیتی را اعمال کنید و میزان استفاده از حسابتان را پیگیری کنید.
برای شروع، یکی را به صورت رایگان در AI Studio ایجاد کنید:
نصب SDK گوگل GenAI
پایتون
با استفاده از پایتون ۳.۹+ ، بسته google-genai را با استفاده از دستور pip زیر نصب کنید:
pip install -q -U google-genai
جاوا اسکریپت
با استفاده از Node.js نسخه ۱۸+ ، کیت توسعه نرمافزاری Google Gen AI را برای TypeScript و JavaScript با استفاده از دستور npm زیر نصب کنید:
npm install @google/genai
تولید متن
از متد models.generate_content برای تولید یک پاسخ متنی استفاده کنید.
پایتون
from google import genai
client = genai.Client()
response = client.models.generate_content(
model="gemini-3.5-flash",
contents="Explain how AI works in a few words"
)
print(response.text)
جاوا اسکریپت
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({});
async function main() {
const response = await ai.models.generateContent({
model: "gemini-3.5-flash",
contents: "Explain how AI works in a few words",
});
console.log(response.text);
}
main();
استراحت
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.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"
}
]
}
]
}'
پاسخهای استریم
به طور پیشفرض، مدل فقط پس از تکمیل کل فرآیند تولید، پاسخ را برمیگرداند. برای یک تجربه سریعتر و تعاملیتر، میتوانید بخشهای پاسخ را همزمان با تولید، پخش کنید .
پایتون
response = client.models.generate_content_stream(
model="gemini-3.5-flash",
contents="Explain how AI works in detail"
)
for chunk in response:
print(chunk.text, end="", flush=True)
جاوا اسکریپت
async function main() {
const responseStream = await ai.models.generateContentStream({
model: "gemini-3.5-flash",
contents: "Explain how AI works in detail",
});
for await (const chunk of responseStream) {
process.stdout.write(chunk.text);
}
}
main();
استراحت
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.5-flash:streamGenerateContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
--no-buffer \
-X POST \
-d '{
"contents": [
{
"parts": [
{
"text": "Explain how AI works in detail"
}
]
}
]
}'
مکالمات چند نوبتی
برای مکالمات چند نوبتی، SDKها یک کمککننده chats حالتدار ارائه میدهند تا یک تجربه چت چند نوبتی ایجاد کنند که به طور خودکار تاریخچه مکالمات را مدیریت میکند.
پایتون
chat = client.chats.create(model="gemini-3.5-flash")
response1 = chat.send_message("I have 2 dogs in my house.")
print("Response 1:", response1.text)
response2 = chat.send_message("How many paws are in my house?")
print("Response 2:", response2.text)
جاوا اسکریپت
async function main() {
const chat = ai.chats.create({ model: "gemini-3.5-flash" });
let response = await chat.sendMessage({ message: "I have 2 dogs in my house." });
console.log("Response 1:", response.text);
response = await chat.sendMessage({ message: "How many paws are in my house?" });
console.log("Response 2:", response.text);
}
main();
استراحت
# REST is stateless. You must pass the full conversation history in the request.
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.5-flash:generateContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-X POST \
-d '{
"contents": [
{
"role": "user",
"parts": [{"text": "I have 2 dogs in my house."}]
},
{
"role": "model",
"parts": [{"text": "That is nice! Two dogs mean you have plenty of company."}]
},
{
"role": "user",
"parts": [{"text": "How many paws are in my house?"}]
}
]
}'
از ابزارها استفاده کنید
با پایهگذاری پاسخها با جستجوی گوگل برای دسترسی به محتوای وب در لحظه، قابلیتهای مدل را گسترش دهید. مدل بهطور خودکار تصمیم میگیرد چه زمانی جستجو کند، پرسوجوها را اجرا میکند و پاسخ را ترکیب میکند.
پایتون
from google import genai
from google.genai import types
config = types.GenerateContentConfig(
tools=[types.Tool(google_search=types.GoogleSearch())]
)
response = client.models.generate_content(
model="gemini-3.5-flash",
contents="Who won the euro 2024?",
config=config
)
print(response.text)
metadata = response.candidates[0].grounding_metadata
if metadata.web_search_queries:
print("\nSearch queries executed:")
for query in metadata.web_search_queries:
print(f" - {query}")
if metadata.grounding_chunks:
print("\nSources:")
for chunk in metadata.grounding_chunks:
print(f" - [{chunk.web.title}]({chunk.web.uri})")
جاوا اسکریپت
async function main() {
const response = await ai.models.generateContent({
model: "gemini-3.5-flash",
contents: "Who won the euro 2024?",
config: {
tools: [{ googleSearch: {} }]
}
});
console.log(response.text);
const metadata = response.candidates[0]?.groundingMetadata;
if (metadata?.webSearchQueries) {
console.log("\nSearch queries executed:");
for (const query of metadata.webSearchQueries) {
console.log(` - ${query}`);
}
}
if (metadata?.groundingChunks) {
console.log("\nSources:");
for (const chunk of metadata.groundingChunks) {
console.log(` - [${chunk.web.title}](${chunk.web.uri})`);
}
}
}
main();
استراحت
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.5-flash:generateContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H "Content-Type: application/json" \
-X POST \
-d '{
"contents": [
{
"parts": [
{"text": "Who won the euro 2024?"}
]
}
],
"tools": [
{
"google_search": {}
}
]
}'
رابط برنامهنویسی Gemini همچنین از ابزارهای داخلی دیگری نیز پشتیبانی میکند:
- اجرای کد : به مدل اجازه میدهد کد پایتون را برای حل مسائل پیچیده ریاضی بنویسد و اجرا کند.
- زمینه URL : به شما امکان میدهد پاسخها را در URLهای صفحات وب خاصی که ارائه میدهید، قرار دهید.
- جستجوی فایل : به شما امکان میدهد فایلها را آپلود کنید و با استفاده از جستجوی معنایی، پاسخها را در محتوای آنها قرار دهید.
- نقشههای گوگل : به شما امکان میدهد پاسخها را در دادههای مکانی قرار دهید و مکانها، مسیرها و نقشهها را جستجو کنید.
- استفاده از کامپیوتر : به مدل اجازه میدهد تا با یک صفحه نمایش مجازی کامپیوتر، صفحه کلید و ماوس برای انجام وظایف تعامل داشته باشد.
فراخوانی توابع سفارشی
از فراخوانی تابع برای اتصال مدلها به ابزارها و APIهای سفارشی خود استفاده کنید. مدل زمان فراخوانی تابع شما را تعیین میکند و یک functionCall را در پاسخ برای اجرای برنامه شما برمیگرداند.
این مثال یک تابع دمای شبیهسازیشده را تعریف میکند و بررسی میکند که آیا مدل میخواهد آن را فراخوانی کند یا خیر.
پایتون
from google import genai
from google.genai import types
weather_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"],
},
}
tools = types.Tool(function_declarations=[weather_function])
config = types.GenerateContentConfig(tools=[tools])
contents = ["What's the temperature in London?"]
response = client.models.generate_content(
model="gemini-3.5-flash",
contents=contents,
config=config,
)
part = response.candidates[0].content.parts[0]
if part.function_call:
fc = part.function_call
print(f"Model requested function: {fc.name} with args {fc.args}")
mock_result = {"temperature": "15C", "condition": "Cloudy"}
contents.append(response.candidates[0].content)
fn_response_part = types.Part.from_function_response(
name=fc.name,
response=mock_result,
id=fc.id
)
contents.append(types.Content(role="user", parts=[fn_response_part]))
final_response = client.models.generate_content(
model="gemini-3.5-flash",
contents=contents,
config=config,
)
print("Final Response:", final_response.text)
جاوا اسکریپت
import { GoogleGenAI, Type } from '@google/genai';
async function main() {
const weatherFunction = {
name: 'get_current_temperature',
description: 'Gets the current temperature for a given location.',
parameters: {
type: Type.OBJECT,
properties: {
location: {
type: Type.STRING,
description: 'The city name, e.g. San Francisco',
},
},
required: ['location'],
},
};
const contents = [{
role: 'user',
parts: [{ text: "What's the temperature in London?" }]
}];
const response = await ai.models.generateContent({
model: 'gemini-3.5-flash',
contents: contents,
config: {
tools: [{ functionDeclarations: [weatherFunction] }],
},
});
if (response.functionCalls && response.functionCalls.length > 0) {
const fc = response.functionCalls[0];
console.log(`Model requested function: ${fc.name}`);
const mockResult = { temperature: "15C", condition: "Cloudy" };
contents.push(response.candidates[0].content);
contents.push({
role: 'user',
parts: [{
functionResponse: {
name: fc.name,
response: mockResult,
id: fc.id
}
}]
});
const finalResponse = await ai.models.generateContent({
model: 'gemini-3.5-flash',
contents: contents,
config: {
tools: [{ functionDeclarations: [weatherFunction] }],
},
});
console.log("Final Response:", finalResponse.text);
}
}
main();
استراحت
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.5-flash:generateContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-X POST \
-d '{
"contents": [
{
"role": "user",
"parts": [{"text": "What'\''s the temperature in London?"}]
}
],
"tools": [
{
"functionDeclarations": [
{
"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"]
}
}
]
}
]
}'
قدم بعدی چیست؟
حالا که کار با رابط برنامهنویسی کاربردی Gemini را شروع کردهاید، برای ساخت برنامههای پیشرفتهتر، راهنماهای زیر را بررسی کنید: