Gemini API, अलग-अलग इनपुट के जवाब में टेक्स्ट आउटपुट जनरेट कर सकता है. इनमें टेक्स्ट, इमेज, वीडियो, और ऑडियो शामिल हैं. इस गाइड में, टेक्स्ट और इमेज इनपुट का इस्तेमाल करके टेक्स्ट जनरेट करने का तरीका बताया गया है. इसमें स्ट्रीमिंग, चैट, और सिस्टम के निर्देशों के बारे में भी बताया गया है.
लेख इनपुट
Gemini API का इस्तेमाल करके टेक्स्ट जनरेट करने का सबसे आसान तरीका यह है कि मॉडल को सिर्फ़ टेक्स्ट वाला एक इनपुट दिया जाए, जैसा कि इस उदाहरण में दिखाया गया है:
from google import genai
client = genai.Client(api_key="GEMINI_API_KEY")
response = client.models.generate_content(
model="gemini-2.0-flash",
contents=["How does AI work?"]
)
print(response.text)
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({ apiKey: "GEMINI_API_KEY" });
async function main() {
const response = await ai.models.generateContent({
model: "gemini-2.0-flash",
contents: "How does AI work?",
});
console.log(response.text);
}
await main();
// import packages here
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, option.WithAPIKey(os.Getenv("GEMINI_API_KEY")))
if err != nil {
log.Fatal(err)
}
defer client.Close()
model := client.GenerativeModel("gemini-2.0-flash")
resp, err := model.GenerateContent(ctx, genai.Text("How does AI work?"))
if err != nil {
log.Fatal(err)
}
printResponse(resp) // helper function for printing content parts
}
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-X POST \
-d '{
"contents": [
{
"parts": [
{
"text": "How does AI work?"
}
]
}
]
}'
इमेज इनपुट
Gemini API, टेक्स्ट और मीडिया फ़ाइलों को मिलाकर बनाए गए मल्टीमोडल इनपुट के साथ काम करता है. यहां दिए गए उदाहरण में, टेक्स्ट और इमेज इनपुट से टेक्स्ट जनरेट करने का तरीका बताया गया है:
from PIL import Image
from google import genai
client = genai.Client(api_key="GEMINI_API_KEY")
image = Image.open("/path/to/organ.png")
response = client.models.generate_content(
model="gemini-2.0-flash",
contents=[image, "Tell me about this instrument"]
)
print(response.text)
import {
GoogleGenAI,
createUserContent,
createPartFromUri,
} from "@google/genai";
const ai = new GoogleGenAI({ apiKey: "GEMINI_API_KEY" });
async function main() {
const image = await ai.files.upload({
file: "/path/to/organ.png",
});
const response = await ai.models.generateContent({
model: "gemini-2.0-flash",
contents: [
createUserContent([
"Tell me about this instrument",
createPartFromUri(image.uri, image.mimeType),
]),
],
});
console.log(response.text);
}
await main();
model := client.GenerativeModel("gemini-2.0-flash")
imgData, err := os.ReadFile(filepath.Join(testDataDir, "organ.jpg"))
if err != nil {
log.Fatal(err)
}
resp, err := model.GenerateContent(ctx,
genai.Text("Tell me about this instrument"),
genai.ImageData("jpeg", imgData))
if err != nil {
log.Fatal(err)
}
printResponse(resp)
# Use a temporary file to hold the base64 encoded image data
TEMP_B64=$(mktemp)
trap 'rm -f "$TEMP_B64"' EXIT
base64 $B64FLAGS $IMG_PATH > "$TEMP_B64"
# Use a temporary file to hold the JSON payload
TEMP_JSON=$(mktemp)
trap 'rm -f "$TEMP_JSON"' EXIT
cat > "$TEMP_JSON" << EOF
{
"contents": [
{
"parts": [
{
"text": "Tell me about this instrument"
},
{
"inline_data": {
"mime_type": "image/jpeg",
"data": "$(cat "$TEMP_B64")"
}
}
]
}
]
}
EOF
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-X POST \
-d "@$TEMP_JSON"
स्ट्रीमिंग आउटपुट
डिफ़ॉल्ट रूप से, टेक्स्ट जनरेट करने की पूरी प्रोसेस पूरी होने के बाद मॉडल जवाब देता है. GenerateContentResponse
के जनरेट होने के साथ-साथ, उसके इंस्टेंस दिखाने के लिए स्ट्रीमिंग का इस्तेमाल करके, तेज़ी से इंटरैक्शन किया जा सकता है.
from google import genai
client = genai.Client(api_key="GEMINI_API_KEY")
response = client.models.generate_content_stream(
model="gemini-2.0-flash",
contents=["Explain how AI works"]
)
for chunk in response:
print(chunk.text, end="")
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({ apiKey: "GEMINI_API_KEY" });
async function main() {
const response = await ai.models.generateContentStream({
model: "gemini-2.0-flash",
contents: "Explain how AI works",
});
for await (const chunk of response) {
console.log(chunk.text);
}
}
await main();
model := client.GenerativeModel("gemini-1.5-flash")
iter := model.GenerateContentStream(ctx, genai.Text("Write a story about a magic backpack."))
for {
resp, err := iter.Next()
if err == iterator.Done {
break
}
if err != nil {
log.Fatal(err)
}
printResponse(resp)
}
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:streamGenerateContent?alt=sse&key=${GEMINI_API_KEY}" \
-H 'Content-Type: application/json' \
--no-buffer \
-d '{
"contents": [
{
"parts": [
{
"text": "Explain how AI works"
}
]
}
]
}'
एक से ज़्यादा बार की गई बातचीत
Gemini SDK की मदद से, चैट में कई बार सवाल पूछे जा सकते हैं और जवाब दिए जा सकते हैं. चैट फ़ॉर्मैट की मदद से, उपयोगकर्ता धीरे-धीरे जवाब पा सकते हैं और कई हिस्सों वाली समस्याओं को हल करने में मदद पा सकते हैं. चैट के लिए एसडीके लागू करने पर, बातचीत के इतिहास को ट्रैक करने के लिए इंटरफ़ेस मिलता है. हालांकि, जवाब देने के लिए, यह उसी generateContent
तरीके का इस्तेमाल करता है जो बैकग्राउंड में काम करता है.
यहां दिए गए कोड के उदाहरण में, चैट को लागू करने का बुनियादी तरीका बताया गया है:
from google import genai
client = genai.Client(api_key="GEMINI_API_KEY")
chat = client.chats.create(model="gemini-2.0-flash")
response = chat.send_message("I have 2 dogs in my house.")
print(response.text)
response = chat.send_message("How many paws are in my house?")
print(response.text)
for message in chat.get_history():
print(f'role - {message.role}',end=": ")
print(message.parts[0].text)
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({ apiKey: "GEMINI_API_KEY" });
async function main() {
const chat = ai.chats.create({
model: "gemini-2.0-flash",
history: [
{
role: "user",
parts: [{ text: "Hello" }],
},
{
role: "model",
parts: [{ text: "Great to meet you. What would you like to know?" }],
},
],
});
const response1 = await chat.sendMessage({
message: "I have 2 dogs in my house.",
});
console.log("Chat response 1:", response1.text);
const response2 = await chat.sendMessage({
message: "How many paws are in my house?",
});
console.log("Chat response 2:", response2.text);
}
await main();
model := client.GenerativeModel("gemini-1.5-flash")
cs := model.StartChat()
cs.History = []*genai.Content{
{
Parts: []genai.Part{
genai.Text("Hello, I have 2 dogs in my house."),
},
Role: "user",
},
{
Parts: []genai.Part{
genai.Text("Great to meet you. What would you like to know?"),
},
Role: "model",
},
}
res, err := cs.SendMessage(ctx, genai.Text("How many paws are in my house?"))
if err != nil {
log.Fatal(err)
}
printResponse(res)
curl https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY \
-H 'Content-Type: application/json' \
-X POST \
-d '{
"contents": [
{
"role": "user",
"parts": [
{
"text": "Hello"
}
]
},
{
"role": "model",
"parts": [
{
"text": "Great to meet you. What would you like to know?"
}
]
},
{
"role": "user",
"parts": [
{
"text": "I have two dogs in my house. How many paws are in my house?"
}
]
}
]
}'
चैट के साथ स्ट्रीमिंग की सुविधा का इस्तेमाल भी किया जा सकता है. इसका उदाहरण यहां दिया गया है:
from google import genai
client = genai.Client(api_key="GEMINI_API_KEY")
chat = client.chats.create(model="gemini-2.0-flash")
response = chat.send_message_stream("I have 2 dogs in my house.")
for chunk in response:
print(chunk.text, end="")
response = chat.send_message_stream("How many paws are in my house?")
for chunk in response:
print(chunk.text, end="")
for message in chat.get_history():
print(f'role - {message.role}', end=": ")
print(message.parts[0].text)
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({ apiKey: "GEMINI_API_KEY" });
async function main() {
const chat = ai.chats.create({
model: "gemini-2.0-flash",
history: [
{
role: "user",
parts: [{ text: "Hello" }],
},
{
role: "model",
parts: [{ text: "Great to meet you. What would you like to know?" }],
},
],
});
const stream1 = await chat.sendMessageStream({
message: "I have 2 dogs in my house.",
});
for await (const chunk of stream1) {
console.log(chunk.text);
console.log("_".repeat(80));
}
const stream2 = await chat.sendMessageStream({
message: "How many paws are in my house?",
});
for await (const chunk of stream2) {
console.log(chunk.text);
console.log("_".repeat(80));
}
}
await main();
model := client.GenerativeModel("gemini-1.5-flash")
cs := model.StartChat()
cs.History = []*genai.Content{
{
Parts: []genai.Part{
genai.Text("Hello, I have 2 dogs in my house."),
},
Role: "user",
},
{
Parts: []genai.Part{
genai.Text("Great to meet you. What would you like to know?"),
},
Role: "model",
},
}
iter := cs.SendMessageStream(ctx, genai.Text("How many paws are in my house?"))
for {
resp, err := iter.Next()
if err == iterator.Done {
break
}
if err != nil {
log.Fatal(err)
}
printResponse(resp)
}
curl https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:streamGenerateContent?alt=sse&key=$GEMINI_API_KEY \
-H 'Content-Type: application/json' \
-X POST \
-d '{
"contents": [
{
"role": "user",
"parts": [
{
"text": "Hello"
}
]
},
{
"role": "model",
"parts": [
{
"text": "Great to meet you. What would you like to know?"
}
]
},
{
"role": "user",
"parts": [
{
"text": "I have two dogs in my house. How many paws are in my house?"
}
]
}
]
}'
कॉन्फ़िगरेशन पैरामीटर
मॉडल को भेजे गए हर प्रॉम्प्ट में ऐसे पैरामीटर होते हैं जिनसे यह कंट्रोल होता है कि मॉडल, जवाब कैसे जनरेट करता है. आपके पास इन पैरामीटर को कॉन्फ़िगर करने या मॉडल को डिफ़ॉल्ट विकल्पों का इस्तेमाल करने की अनुमति देने का विकल्प होता है.
यहां दिए गए उदाहरण में, मॉडल पैरामीटर को कॉन्फ़िगर करने का तरीका बताया गया है:
from google import genai
from google.genai import types
client = genai.Client(api_key="GEMINI_API_KEY")
response = client.models.generate_content(
model="gemini-2.0-flash",
contents=["Explain how AI works"],
config=types.GenerateContentConfig(
max_output_tokens=500,
temperature=0.1
)
)
print(response.text)
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({ apiKey: "GEMINI_API_KEY" });
async function main() {
const response = await ai.models.generateContent({
model: "gemini-2.0-flash",
contents: "Explain how AI works",
config: {
maxOutputTokens: 500,
temperature: 0.1,
},
});
console.log(response.text);
}
await main();
model := client.GenerativeModel("gemini-1.5-pro-latest")
model.SetTemperature(0.9)
model.SetTopP(0.5)
model.SetTopK(20)
model.SetMaxOutputTokens(100)
model.SystemInstruction = genai.NewUserContent(genai.Text("You are Yoda from Star Wars."))
model.ResponseMIMEType = "application/json"
resp, err := model.GenerateContent(ctx, genai.Text("What is the average size of a swallow?"))
if err != nil {
log.Fatal(err)
}
printResponse(resp)
curl https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY \
-H 'Content-Type: application/json' \
-X POST \
-d '{
"contents": [
{
"parts": [
{
"text": "Explain how AI works"
}
]
}
],
"generationConfig": {
"stopSequences": [
"Title"
],
"temperature": 1.0,
"maxOutputTokens": 800,
"topP": 0.8,
"topK": 10
}
}'
यहां कुछ मॉडल पैरामीटर दिए गए हैं, जिन्हें कॉन्फ़िगर किया जा सकता है. (नेमिंग कन्वेंशन, प्रोग्रामिंग भाषा के हिसाब से अलग-अलग होते हैं.)
stopSequences
: यह कैरेक्टर सीक्वेंस (ज़्यादा से ज़्यादा पांच) का सेट तय करता है, जिससे आउटपुट जनरेशन बंद हो जाएगा. अगर एपीआई कोstop_sequence
के दिखने पर रुकने के लिए कहा जाता है, तो वह ऐसा करेगा. जवाब के हिस्से के तौर पर, स्टॉप सीक्वेंस को शामिल नहीं किया जाएगा.temperature
: इससे आउटपुट में रैंडमिटी को कंट्रोल किया जाता है. ज़्यादा क्रिएटिव जवाबों के लिए ज़्यादा वैल्यू और ज़्यादा तय जवाबों के लिए कम वैल्यू का इस्तेमाल करें. वैल्यू [0.0, 2.0] के बीच हो सकती हैं.maxOutputTokens
: किसी उम्मीदवार में शामिल करने के लिए, ज़्यादा से ज़्यादा टोकन की संख्या सेट करता है.topP
: इससे, मॉडल के आउटपुट के लिए टोकन चुनने के तरीके में बदलाव होता है. टोकन को सबसे ज़्यादा से कम संभावित तक चुना जाता है, जब तक कि उनकी संभावनाओं का योगtopP
वैल्यू के बराबर न हो जाए.topP
की डिफ़ॉल्ट वैल्यू 0.95 है.topK
: इससे, मॉडल के आउटपुट के लिए टोकन चुनने के तरीके में बदलाव होता है.topK
के 1 होने का मतलब है कि चुना गया टोकन, मॉडल की शब्दावली के सभी टोकन में से सबसे ज़्यादा संभावना वाला टोकन है. वहीं,topK
के 3 होने का मतलब है कि अगला टोकन, टेम्परेचर का इस्तेमाल करके सबसे ज़्यादा संभावना वाले तीन टोकन में से चुना जाता है.topP
के आधार पर टोकन को और फ़िल्टर किया जाता है. इसके बाद, टेंपरेचर सैंपलिंग का इस्तेमाल करके फ़ाइनल टोकन चुना जाता है.
सिस्टम से जुड़े निर्देश
सिस्टम के निर्देशों की मदद से, अपने इस्तेमाल के उदाहरण के आधार पर मॉडल के व्यवहार को कंट्रोल किया जा सकता है. सिस्टम के लिए निर्देश देने पर, मॉडल को टास्क को समझने और ज़्यादा बेहतर जवाब देने में मदद करने के लिए, अतिरिक्त कॉन्टेक्स्ट दिया जाता है. मॉडल को उपयोगकर्ता के साथ पूरे इंटरैक्शन के दौरान, सिस्टम के निर्देशों का पालन करना चाहिए. इससे, आपको असली उपयोगकर्ताओं के दिए गए प्रॉम्प्ट से अलग, प्रॉडक्ट-लेवल के व्यवहार के बारे में बताने में मदद मिलती है.
मॉडल को शुरू करते समय, सिस्टम के निर्देश सेट किए जा सकते हैं:
from google import genai
from google.genai import types
client = genai.Client(api_key="GEMINI_API_KEY")
response = client.models.generate_content(
model="gemini-2.0-flash",
config=types.GenerateContentConfig(
system_instruction="You are a cat. Your name is Neko."),
contents="Hello there"
)
print(response.text)
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({ apiKey: "GEMINI_API_KEY" });
async function main() {
const response = await ai.models.generateContent({
model: "gemini-2.0-flash",
contents: "Hello there",
config: {
systemInstruction: "You are a cat. Your name is Neko.",
},
});
console.log(response.text);
}
await main();
// import packages here
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, option.WithAPIKey(os.Getenv("GEMINI_API_KEY")))
if err != nil {
log.Fatal(err)
}
defer client.Close()
model := client.GenerativeModel("gemini-2.0-flash")
model.SystemInstruction = &genai.Content{
Parts: []genai.Part{genai.Text(`
You are a cat. Your name is Neko.
`)},
}
resp, err := model.GenerateContent(ctx, genai.Text("Hello there"))
if err != nil {
log.Fatal(err)
}
printResponse(resp) // helper function for printing content parts
}
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"system_instruction": {
"parts": [
{
"text": "You are a cat. Your name is Neko."
}
]
},
"contents": [
{
"parts": [
{
"text": "Hello there"
}
]
}
]
}'
इसके बाद, मॉडल को हमेशा की तरह अनुरोध भेजे जा सकते हैं.
काम करने वाले मॉडल
Gemini के सभी मॉडल, टेक्स्ट जनरेट करने की सुविधा के साथ काम करते हैं. मॉडल और उनकी सुविधाओं के बारे में ज़्यादा जानने के लिए, मॉडल देखें.
प्रॉम्प्ट के बारे में सलाह
टेक्स्ट जनरेशन के बुनियादी इस्तेमाल के उदाहरणों के लिए, हो सकता है कि आपके प्रॉम्प्ट में आउटपुट के उदाहरण, सिस्टम के निर्देश या फ़ॉर्मैटिंग की जानकारी शामिल न हो. यह ज़ीरो-शॉट वाला तरीका है. कुछ इस्तेमाल के उदाहरणों के लिए, एक-शॉट या कुछ-शॉट प्रॉम्प्ट से ऐसा आउटपुट मिल सकता है जो उपयोगकर्ता की उम्मीदों के मुताबिक हो. कुछ मामलों में, मॉडल को टास्क समझने या खास दिशा-निर्देशों का पालन करने में मदद करने के लिए, सिस्टम के निर्देश भी दिए जा सकते हैं.
आगे क्या करना है
- Gemini API का इस्तेमाल शुरू करने के लिए Colab को आज़माएं.
- इमेज और वीडियो को प्रोसेस करने के लिए, Gemini के विज़न को समझने की सुविधा का इस्तेमाल करने का तरीका जानें.
- ऑडियो फ़ाइलों को प्रोसेस करने के लिए, Gemini के ऑडियो समझने की सुविधा का इस्तेमाल करने का तरीका जानें.
- अलग-अलग तरीकों से फ़ाइल अपलोड करने के लिए कहा जाने की रणनीतियों के बारे में जानें.