Webhook-et i lejojnë API-t Gemini të dërgojë njoftime në kohë reale në serverin tuaj kur përfundojnë Operacionet asinkrone ose Operacionet me Ekzekutim të Gjatë (LRO). Kjo zëvendëson nevojën për të pyetur API-n për përditësimet e statusit, duke zvogëluar vonesën dhe mbingarkesën.
Webhook-et janë të disponueshëm për operacione si punë në grup , ndërveprime dhe gjenerim videosh .
Si funksionon
Në vend që të pyetni GET /operations në mënyrë të përsëritur për të kontrolluar nëse një punë është përfunduar, mund të konfiguroni Gemini API Webhooks për të dërguar një kërkesë HTTP POST në URL-në tuaj të dëgjuesit menjëherë pas një shkaktimi të ngjarjes.
API-ja Gemini mbështet dy mënyra për të konfiguruar webhook-et:
- Webhook-e statikë : Pikat fundore në nivel projekti të konfiguruara me API-në Gemini WebhookService . I mirë për integrime globale (p.sh., njoftimi i Slack, sinkronizimi i një baze të dhënash, etj.).
- Webhook-e dinamike : Mbivendosjet në nivel kërkese kalojnë një URL webhook në ngarkesën e konfigurimit të një thirrjeje specifike të punëve. Ideale për drejtimin e punëve specifike në pikat fundore të dedikuara.
Webhook-e statikë
Webhook-et statikë regjistrohen për një projekt të tërë dhe aktivizohen për çdo ngjarje që përputhet.
Krijo një webhook
Mund të krijoni pika fundore duke përdorur SDK ose REST API.
E RËNDËSISHME : Kur krijoni një webhook, API kthen një sekret nënshkrimi vetëm një herë . Duhet ta ruani këtë në mënyrë të sigurt (p.sh. në variablat e mjedisit tuaj) për të verifikuar nënshkrimet më vonë. Nëse e humbni sekretin e nënshkrimit, do t'ju duhet ta rrotulloni atë.
Python
from google import genai
client = genai.Client()
webhook = client.webhooks.create(
name="MyBatchWebhook",
subscribed_events=["batch.completed", "batch.failed"],
uri="https://my-api.com/gemini-callback",
)
# Store webhook.new_signing_secret securely
webhook_secret = webhook.new_signing_secret
print(f"Created webhook: {webhook.name}, {webhook.id}")
JavaScript
import { GoogleGenAI } from "@google/genai";
const client = new GoogleGenAI();
async function createWebhook() {
const webhook = await client.webhooks.create({
name: "MyBatchWebhook",
subscribed_events: ["batch.completed", "batch.failed"],
uri: "https://my-api.com/gemini-callback",
});
// Store webhook.signingSecret securely
const webhookSecret = webhook.new_signing_secret;
console.log(`Created webhook: ${webhook.name}, ${webhook.id}`);
}
createWebhook();
PUSHTIM
curl -X POST \
"https://generativelanguage.googleapis.com/v1/webhooks" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GOOGLE_API_KEY" \
-d '{
"name": "MyBatchWebhook",
"uri": "https://my-api.com/gemini-callback",
"subscribed_events": ["batch.completed", "batch.failed"]
}'
Për detaje mbi konfigurimin e serverit tuaj për të marrë të dhëna, shihni seksionin Handle webhook requests .
Merrni një webhook
Merrni detaje rreth një webhook-u specifik sipas emrit të burimit të tij.
Python
from google import genai
client = genai.Client()
webhook = client.webhooks.get(id="<your_webhook_id>")
print(f"Webhook: {webhook.name}")
print(f"URI: {webhook.uri}")
print(f"Events: {webhook.subscribed_events}")
JavaScript
import { GoogleGenAI } from "@google/genai";
const client = new GoogleGenAI(); // Assumes process.env.GEMINI_API_KEY is set
async function getWebhook() {
const webhook = await client.webhooks.get("<your_webhook_id>");
console.log(`Webhook: ${webhook.name}`);
console.log(`URI: ${webhook.uri}`);
console.log(`Events: ${webhook.subscribed_events}`);
}
getWebhook();
PUSHTIM
curl -X GET \
"https://generativelanguage.googleapis.com/v1/webhooks/<your_webhook_id>" \
-H "x-goog-api-key: $GOOGLE_API_KEY"
Listoni webhook-et
Listoni të gjitha webhook-et e konfiguruara për projektin aktual, me faqosje opsionale.
Python
from google import genai
client = genai.Client()
webhooks = client.webhooks.list()
for wh in webhooks:
print(f"{wh.id}: {wh.name} -> {wh.uri}")
JavaScript
import { GoogleGenAI } from "@google/genai";
const client = new GoogleGenAI();
async function listWebhooks() {
const webhooks = await client.webhooks.list();
for (const wh of webhooks) {
console.log(`${wh.id}: ${wh.name} -> ${wh.uri}`);
}
}
listWebhooks();
PUSHTIM
curl -X GET \
"https://generativelanguage.googleapis.com/v1/webhooks" \
-H "x-goog-api-key: $GOOGLE_API_KEY"
Përditëso një webhook
Përditësoni vetitë e një webhook-u ekzistues, siç janë emri i shfaqjes, URI-ja e synuar ose ngjarjet e abonuara.
Python
from google import genai
client = genai.Client()
updated_webhook = client.webhooks.update(
id="<your_webhook_id>",
subscribed_events=["batch.completed", "batch.failed", "batch.cancelled"],
)
print(f"Updated webhook: {updated_webhook.name}")
JavaScript
import { GoogleGenAI } from "@google/genai";
const client = new GoogleGenAI();
async function updateWebhook() {
const updatedWebhook = await client.webhooks.update(
"<your_webhook_id>",
{
subscribed_events: ["batch.completed", "batch.failed", "batch.cancelled"],
}
);
console.log(`Updated webhook: ${updatedWebhook.name}`);
}
updateWebhook();
PUSHTIM
curl -X PATCH \
"https://generativelanguage.googleapis.com/v1/webhooks/<your_webhook_id>" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GOOGLE_API_KEY" \
-d '{
"subscribed_events": ["batch.completed", "batch.failed", "batch.cancelled"]
}'
Fshi një webhook
Hiq një pikë fundore webhook nga projekti. Kjo ndalon dërgesat e ardhshme të ngjarjeve në atë pikë fundore.
Python
from google import genai
client = genai.Client()
client.webhooks.delete(id="<your_webhook_id>")
print("Webhook deleted.")
JavaScript
import { GoogleGenAI } from "@google/genai";
const client = new GoogleGenAI();
async function deleteWebhook() {
await client.webhooks.delete("<your_webhook_id>");
console.log("Webhook deleted.");
}
deleteWebhook();
PUSHTIM
curl -X DELETE \
"https://generativelanguage.googleapis.com/v1/webhooks/<your_webhook_id>" \
-H "x-goog-api-key: $GOOGLE_API_KEY"
Rrotulloni një sekret nënshkrimi
Rrotulloni sekretin e nënshkrimit për një webhook. Mund të konfiguroni nëse sekretet e mëparshme aktive revokohen menjëherë apo pas një periudhe pritjeje 24-orëshe.
E RËNDËSISHME : Sekreti i ri i nënshkrimit kthehet vetëm një herë në kohën e rrotullimit. Ruajeni atë në mënyrë të sigurt përpara se të përditësoni logjikën e verifikimit.
Python
from google import genai
from google.genai import types
client = genai.Client()
response = client.webhooks.rotate_signing_secret(
id="<your_webhook_id>",
revocation_behavior="REVOKE_PREVIOUS_SECRETS_AFTER_H24",
)
# Store response.secret securely, then update your server's verification config
print("New signing secret generated. Update your server configuration.")
JavaScript
import { GoogleGenAI } from "@google/genai";
const client = new GoogleGenAI();
async function rotateSigningSecret() {
const response = await client.webhooks.rotateSigningSecret(
"<your_webhook_id>",
{
revocation_behavior: "REVOKE_PREVIOUS_SECRETS_AFTER_H24",
}
);
// Store response.secret securely, then update your server's verification config
console.log("New signing secret generated. Update your server configuration.");
}
rotateSigningSecret();
PUSHTIM
curl -X POST \
"https://generativelanguage.googleapis.com/v1/webhooks/<your_webhook_id>/rotate_secret" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GOOGLE_API_KEY" \
-d '{
"revocation_behavior": "REVOKE_PREVIOUS_SECRETS_AFTER_H24"
}'
Trajtoni kërkesat e webhook në një server
Kur ndodh një ngjarje në të cilën jeni abonuar, URL-ja juaj e webhook-ut do të marrë një kërkesë HTTP POST. Pika juaj fundore duhet të përgjigjet me një kod statusi 2xx brenda pak sekondash për të shmangur një riprovë. Për të siguruar dorëzimin, API-ja Gemini riprovon automatikisht kërkesat e dështuara për 24 orë duke përdorur tërheqje eksponenciale.
Gemini ndjek në mënyrë strikte specifikimin Standard Webhooks për titrat e sigurisë. Verifikoni ngarkesën në serverin tuaj duke përdorur nënshkrimet e nënshkruara të titrave dhe sekretin e ruajtur të nënshkrimit statik. Shihni seksionin e zarfit të Webhook për informacionin e ngarkesës.
Ja një shembull duke përdorur Flask për dëgjuesin HTTP:
Python
# pip install flask standardwebhooks
import os
from flask import Flask, request, jsonify
# Standard verification wrapper for Standard Webhook Headers
from standardwebhooks.webhooks import Webhook, WebhookVerificationError
app = Flask(__name__)
SIGNING_SECRET = os.environ.get('WEBHOOK_SIGNING_SECRET')
@app.route('/gemini-callback', methods=['POST'])
def gemini_callback():
payload = request.get_data(as_text=True)
headers = request.headers
try:
wh = Webhook(SIGNING_SECRET)
event = wh.verify(payload, headers)
except WebhookVerificationError as e:
return jsonify({"error": "Signature invalid"}), 400
# Process thin payload contents
if event.get("type") in ("batch.completed", "video.generated"):
uri = event['data']['output_file_uri']
print(f"Batch finished! Results at: {uri}")
return jsonify({"status": "received"}), 200
if __name__ == "__main__":
app.run(port=8000)
JavaScript
// npm install standardwebhooks
import { Webhook } from "standardwebhooks";
import express from "express";
const app = express();
const client = new GoogleGenAI({ webhookSecret: process.env.WEBHOOK_SIGNING_SECRET });
// Don't use express.json() because signature verification needs the raw text body
app.use(express.text({ type: "application/json" }));
app.post("/gemini-callback", async (req, res) => {
const payload = await req.text();
const headers: Record<string, string> = {};
req.headers.forEach((value, key) => {
headers[key] = value;
});
try {
const wh = new Webhook(process.env.WEBHOOK_SIGNING_SECRET);
const event = wh.verify(payload, headers) as Record<string, any>;
// Process thin payload contents
if (event.type === "batch.completed" || event.type === "video.generated") {
const uri = event.data.output_file_uri;
console.log(`Job finished! Results at: ${uri}`);
}
res.status(200).json({ status: "received" });
} catch (e) {
console.error("Webhook verification failed:", e);
res.status(400).send("Invalid signature");
}
});
app.listen(8000, () => {
console.log("Webhook server is running on port 8000");
});
Webhook-e dinamikë
Webhook-et dinamikë ju lejojnë të lidhni një pikë fundore të webhook-ut me një konfigurim specifik kërkese , ideal për radhët e orkestrimit të agjentëve. Webhook-et dinamikë shfrytëzojnë nënshkrimet JWKS me çelës publik asimetrik në vend të sekreteve simetrike.
Dorëzoni një kërkesë dinamike
Shtoni një webhook_config kur aktivizoni një punë asinkrone (p.sh., duke krijuar një Batch).
Python
from google import genai
from google.genai import types
client = genai.Client()
file_batch_job = client.batches.create(
model="gemini-3-flash-preview",
src="files/uploaded_file_id",
config={
"display_name": "My Setup",
"webhook_config": {
"uris": ["https://my-api.com/gemini-webhook-dynamic"],
"user_metadata":{"job_group": "nightly-eval", "priority": "high"}
}
}
)
JavaScript
import { GoogleGenAI } from "@google/genai";
const client = new GoogleGenAI();
async function createBatchWithWebhook() {
const fileBatchJob = await client.batches.create({
model: "gemini-3-flash-preview",
src: "files/uploaded_file_id",
config: {
displayName: "My Setup",
webhookConfig: {
uris: ["https://my-api.com/gemini-webhook-dynamic"],
user_metadata: {"job_group": "nightly-eval", "priority": "high"}
},
},
});
}
PUSHTIM
curl -X POST \
"https://generativelanguage.googleapis.com/v1/models/gemini-3-flash-preview:batchCreate" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GOOGLE_API_KEY" \
-d '{
"src": "files/uploaded_file_id",
"config": {
"display_name": "My Setup",
"webhook_config": {
"uris": ["https://my-api.com/gemini-webhook-dynamic"],
"user_metadata": {"job_group": "nightly-eval", "priority": "high"}
}
}
}'
Verifikoni nënshkrimet dinamike (JWKS)
Kërkesat dinamike të webhook-ut lëshojnë një nënshkrim JSON Web Token (JWT). Dëgjuesi juaj duhet ta nxjerrë nënshkrimin dhe ta verifikojë atë duke përdorur pikat fundore të certifikatës publike të Google-it .
Python
import jwt
import requests
from flask import Flask, request, jsonify
app = Flask(__name__)
# Google public cert list endpoint
JWKS_URI = "https://generativelanguage.googleapis.com/.well-known/jwks.json"
def load_google_public_key(kid):
response = requests.get(JWKS_URI).json()
for key_item in response.get('keys', []):
if key_item.get('kid') == kid:
# Convert JWK to Cert wrapper
return jwt.algorithms.RSAAlgorithm.from_jwk(key_item)
return None
@app.route('/gemini-webhook-dynamic', methods=['POST'])
def dynamic_handler():
payload = request.get_data(as_text=True)
headers = request.headers
token = headers.get('Webhook-Signature')
if not token:
return jsonify({"error": "No signature header"}), 400
try:
# Extract kid from JWT header
unverified_headers = jwt.get_unverified_header(token)
pub_key = load_google_public_key(unverified_headers.get('kid'))
if not pub_key:
return jsonify({"error": "Key cert not found"}), 400
# Verify Signature against expected audience (e.g., your project client ID)
event = jwt.decode(
token,
pub_key,
algorithms=["RS256"],
audience="your-configured-audience"
)
except Exception as e:
return jsonify({"error": "Invalid Dynamic signature", "details": str(e)}), 400
print("Verified Dynamic payload success.")
return jsonify({"status": "received"}), 200
JavaScript
import { GoogleGenAI } from "@google/genai";
import express from "express";
import jwt from "jsonwebtoken";
import jwksClient from "jwks-rsa";
const app = express();
app.use(express.text({ type: 'application/json' }));
const client = jwksClient({
jwksUri: "https://generativelanguage.googleapis.com/.well-known/jwks.json"
});
function getKey(header, callback) {
client.getSigningKey(header.kid, (err, key) => {
const signingKey = key.getPublicKey();
callback(null, signingKey);
});
}
app.post('/gemini-webhook-dynamic', (req, res) => {
const token = req.headers['webhook-signature'];
if (!token) {
return res.status(400).json({ error: "No signature header" });
}
jwt.verify(
token,
getKey,
{
algorithms: ["RS256"],
audience: "your-configured-audience"
},
(err, decoded) => {
if (err) {
return res.status(400).json({ error: "Invalid Dynamic signature", details: err.message });
}
console.log("Verified Dynamic payload success.");
res.status(200).json({ status: "received" });
}
);
});
Zarf Webhook
Për të shmangur mbingarkesën e bandwidth-it, webhook-et Gemini përdorin një model të hollë ngarkese për të ofruar të dhëna. Dërgesat dërgojnë një pamje të çastit që përmban detajet e statusit dhe treguesit e rezultateve, në vend të vetë skedarit të papërpunuar të daljes.
Ja një shembull i formatit të ngarkesës:
{
"type": "batch.completed",
"version": "v1",
"timestamp": "2026-01-22T12:00:00Z",
"data": {
"id": "batch_123456",
"output_file_uri": "gs://my-bucket/results.jsonl",
"error_count": 0
}
}
Referenca e katalogut të ngjarjeve
Ngjarjet e mëposhtme shkaktohen për punët mbështetëse:
| Lloji i ngjarjes | Shkaktues | Elementi i ngarkesës ( data ) |
|---|---|---|
batch.succeeded | Përpunimi përfundoi me sukses. | id , output_file_uri |
batch.cancelled | Përdoruesi anuloi kërkesën | id |
batch.expired | Grupi nuk është përpunuar (përfunduar) brenda afatit kohor 24-orësh | id |
batch.failed | Puna në grup dështoi (gabim sistemi ose validimi). | id , error_code , error_message |
interaction.requires_action | Thirrja e funksionit, përdoruesi duhet të bëjë diçka | id |
interaction.completed | LRO në API-në e ndërveprimeve pati sukses. | id |
interaction.failed | LRO në API-në e ndërveprimeve dështoi (gabim sistemi ose validimi). | id , error_code , error_message |
interaction.cancelled | LRO në API-në e ndërveprimeve u anulua. | id |
video.generated | Gjenerimi i videos LRO përfundoi. | file_id , video_uri |
Praktikat më të mira
Për të siguruar një funksionim të besueshëm dhe të shkallëzueshëm:
- Kontroll i rreptë i mbrojtjes nga riluajtja : Të gjitha kërkesat mbajnë një kokë të
webhook-timestamp. Gjithmonë validoni këtë pullë kohore në shtresën e konfigurimit të serverit tuaj për të refuzuar ngarkesat më të vjetra se 5 minuta (për të zbutur sulmet e riluajtjes). - Përpunoni në mënyrë asinkrone : Përgjigjuni me
2xx OKmenjëherë pas zbulimit të nënshkrimit të vlefshëm dhe vendosni operacionet e analizimit në radhë brenda vendit. Kohëzgjatja e zgjatur e mbajtjes së dëgjuesit do të shkaktojë një cikël ripërpjekjeje për dorëzim. - Trajtimi i heqjes së dyfishimeve : Webhook-et standarde ofrojnë "Të paktën një herë". Përdorni kokën konsistente
webhook-idpër të trajtuar dyfishimet e mundshme në rrjedhat me mbingarkesë më të lartë.
Çfarë vjen më pas?
- Batch API : Përdorni webhook-e për të automatizuar pikat fundore me volum të lartë.