Gemini 2.5 – Outils & Intégrations
SDK Vertex AI & tools/function calling, RAG avec Vertex AI Search, automatisations GCP (Scheduler/Run/Build), intégrations IDE & Cloud.
Vertex AI SDK : appels, streaming & tools / function calling
Intégration standard : GenerativeModel (Gemini 2.5 Pro), configuration stricte (température, JSON typé), streaming pour l’UX, et tools (function calling) pour déléguer des actions contrôlées.
🔐 Pré-requis
pip install google-cloud-aiplatform,import vertexai; auth ADC (gcloud auth application-default login).- Préciser projet, région, modèle, et activer la journalisation (latence/tokens/coût).
from vertexai.generative_models import GenerativeModel, GenerationConfig, ResponseSchema, Tool, FunctionDeclaration
# 1) Modèle + configuration JSON strict
schema = ResponseSchema(type="object", properties={
"files":{"type":"array","items":{"type":"object","properties":{
"path":{"type":"string"},"action":{"type":"string","enum":["create","patch"]},"content":{"type":"string"}}}},
"commands":{"type":"array","items":{"type":"string"}}
}, required=["files"])
cfg = GenerationConfig(temperature=0.2, response_mime_type="application/json", response_schema=schema)
model = GenerativeModel("gemini-2.5-pro")
# 2) Tools / function calling
tool = Tool(function_declarations=[
FunctionDeclaration(
name="lookup_doc",
description="Recherche interne par mot-clé.",
parameters={"type":"object","properties":{"query":{"type":"string"}},"required":["query"]}
)
])
# 3) Appel (non-streaming)
prompt = "Crée un modèle Django Article + admin. Bloc par fichier, tests, et commandes manage.py."
resp = model.generate_content(prompt, generation_config=cfg, tools=[tool])
# Examiner resp.candidates[0].content.parts → tool calls éventuels / JSON🌊 Streaming (UI fluide)
for event in model.generate_content_stream(prompt, generation_config=cfg):
# event.text / event.candidates ... (pousser dans SSE/WebSocket)🧱 Prompt “safe-by-default” (à réutiliser)
RÔLE : Développeur senior Django
FORMAT : JSON (schéma) ; si modif → DIFF UNIFIÉ dans 'content'
BORNES : ≤ 120 lignes cumulées ; sinon STOP & pose 1 question
SELF-CHECK : rappelle contraintes, donne 2 alternatives + justification
VÉRIF : commandes manage.py + tests pytestVertex AI Search & RAG : ingestion, retrieval, citations
Un RAG robuste = ingestion (chunking + embeddings), stockage, retrieval (top-k + rerank), génération ancrée avec citations, et évaluation.
🏗️ Pipeline (règles pratiques)
- Split 500–1000 tokens, overlap 50–150.
- Normaliser (enlever HTML hostile, métadonnées utiles : doc_id/chunk_id/page).
- Indexer (Vertex AI Search / PGVector / FAISS).
- Retrieve top-k puis rerank si besoin.
- Générer en citant explicitement source + ligne.
- Évaluer : groundedness, coverage, exact match.
🐍 Exemple “search + synthèse ancrée”
def synthese_avec_citations(query: str):
# 1) récupérer des passages (ex: Vertex AI Search SDK / API REST)
passages = [{"source":"kb://rgpd#12","text":"..."} for _ in range(5)]
ctx = "\n\n".join(f"[{p['source']}]\n{p['text']}" for p in passages)
# 2) demander à Gemini de répondre SEULEMENT à partir de ces passages
sys = ("Tu dois te limiter aux extraits fournis. "
"Réponds avec des citations [source]. Si info absente, dis-le.")
prompt = f"{sys}\n\nEXTRAITS:\n{ctx}\n\nQUESTION: {query}"
r = model.generate_content(prompt, generation_config=GenerationConfig(temperature=0.1))
return r.text🛡️ Sécurité RAG
- Sanitizer anti prompt-injection (strip scripts/instructions, allow-list d’outils).
- Limiter aux sources “fiables” et afficher les citations en sortie.
- Stocker les références pour audit (doc_id, chunk_id, score).
Automatisations : Scheduler → Cloud Run/Functions, Cloud Build, Observabilité
Industrialiser les traitements IA : jobs planifiés, pipelines CI/CD, scripts idempotents, métriques de coûts/tokens/latence.
⏰ Scheduler → HTTP Cloud Run
# CLI
gcloud scheduler jobs create http daily-summary \
--schedule="0 7 * * *" --uri="https://run.app/summary" --http-method=POST \
--oidc-service-account-email=cron-sa@PROJECT.iam.gserviceaccount.com🐍 Handler Cloud Run (extrait)
from flask import Flask, request
app = Flask(__name__)
@app.post("/summary")
def gen():
text = request.get_json().get("text","")
r = model.generate_content(f"Résume en 5 puces:\n{text}",
generation_config=GenerationConfig(temperature=0.3))
return {"ok": True, "summary": r.text}🚀 Cloud Build (lint + tests + build + deploy)
steps:
- name: python
entrypoint: bash
args: ["-lc","pip install -r requirements.txt && ruff check && pytest -q"]
- name: gcr.io/cloud-builders/gcloud
args: ["run","deploy","ideolab-api","--source=.","--region=us-central1"]
options: {logging: CLOUD_LOGGING_ONLY}📊 Observabilité
- Logs structurés (latence p95, tokens in/out, coût, taux d’erreurs/quotas).
- Alertes budgets + erreurs 5xx/429 ; tableaux de bord (Cloud Logging / Metrics).
IDE & Cloud : VSCode, JetBrains, Cloud Shell/Colab
Amener Gemini dans le flux dev : actions sur sélection, snippets “bloc par fichier”, tests rapides, et environnements Cloud prêts-à-l’emploi.
🧩 Extensions utiles
- Chat/Actions in-editor ; génération/refactor/test sur sélection.
- REST/HTTP client pour frapper tes endpoints Vertex/Run.
- GitLens/PR tools pour auditer le diff livré par l’IA.
🧠 Workflows gagnants
- “Explique / Refactor / Teste ce code” + collage du STATE PACK.
- Commandes intégrées :
manage.py,pytest,npm run build. - Cloud Shell Editor/Colab : notebooks d’essai, prototypage rapide.
🛡️ Bonnes pratiques
- Secrets dans
Secret Manager/ variables d’environnement ; jamais en clair. - Linters “on save”, diff obligatoire, tests avant merge.
