SPB Git

Repository Public

grounding.py 5.4 KB 116 lines python

1#!/usr/bin/env python32# =============================================================================3#                  SP BOUCHER | SOFTWARE & RESEARCH4#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5# =============================================================================6#7# PROJECT METADATA8# -----------------------------------------------------------------------------9# Project          : API Atlas10# File             : examples/gemini/tools/google-search/grounding.py11# Description      : Grounding with Google Search (`tools: [{"googleSearch":12#                    {}}]`) and the groundingMetadata anatomy.13# Module           : examples14# Repository       : https://git.spboucher.ai/doc-api15# Created          : 2026-09-1916# Last Modified    : 2026-09-1917#18# =============================================================================19# AUTHOR & PROFESSIONAL AFFILIATION20# =============================================================================21#22# Author           : Simon-Pierre Boucher23# Position         : Professor of Finance24# Institution      : Université du Québec en Outaouais (UQO)25# Department       : Département des sciences administratives26# Organization     : SP Boucher27#28# Website          : https://spboucher.ai29# Git              : https://git.spboucher.ai30#31# =============================================================================32# OFFICIAL CONTACT DIRECTORY33# =============================================================================34#35# General          : info@spboucher.ai36# Professional     : contact@spboucher.ai37# Direct           : simon@spboucher.ai38# Research         : research@spboucher.ai39# Development      : dev@spboucher.ai40# Support          : support@spboucher.ai41# Security/Admin   : admin@spboucher.ai42# Notifications    : notifications@spboucher.ai43#44# Preferred Contact: contact@spboucher.ai45#46# =============================================================================47# COPYRIGHT & INTELLECTUAL PROPERTY48# =============================================================================49#50# Copyright (c) 202651# Simon-Pierre Boucher52#53# All rights reserved where applicable.54#55# This file is governed by the applicable project license,56# copyright notices, institutional agreements and relevant law.57#58# Unless expressly authorized by the applicable license or59# rights holder, copying, redistribution, sublicensing,60# publication and commercial exploitation are not permitted.61#62# Existing third-party rights and notices remain unaffected.63#64# =============================================================================65# CONFIDENTIALITY & SECURITY66# =============================================================================67#68# Classification   : Public69# Distribution     : Public repository; use is governed by the project license70# Security Contact : admin@spboucher.ai71#72# Access to this source does not independently grant permission73# to redistribute or disclose confidential materials.74#75# Do not embed credentials, private keys, access tokens,76# certificates or confidential personal information.77#78# =============================================================================79# LICENSE & MAINTENANCE80# =============================================================================81#82# License          : None specified (no license file in this repository)83# Maintainer       : Simon-Pierre Boucher84# Technical Contact: dev@spboucher.ai85#86# =============================================================================87# END OF SP BOUCHER SOURCE HEADER88# =============================================================================8990"""Grounding with Google Search (`tools: [{"googleSearch": {}}]`) and the groundingMetadata anatomy.91STATUS: ACCOUNT_RESTRICTED 2026-09-18 — our key returned HTTP 429 RESOURCE_EXHAUSTED ("You exceeded your current quota") on92gemini-3.5-flash-lite AND gemini-3.5-flash (tmp-live/gemini-tools/b_google_search.json, b2_google_search_flash.json): the project is93on a tier where Search grounding is "Not available" (pricing page: free tier). The request shape below is the documented one.94Run: .venv/bin/python examples/gemini/tools/google-search/grounding.py95"""96import json, sys97from pathlib import Path98sys.path.insert(0, str(Path(__file__).resolve().parents[4]))99from scripts.live import gemini_request100MODEL = "gemini-3.5-flash-lite"101st, r, _ = gemini_request("POST", f"/v1beta/models/{MODEL}:generateContent",102                          {"contents": [{"parts": [{"text": "What is today's date in Toronto? 5 words."}]}], "tools": [{"googleSearch": {}}],103                           "generationConfig": {"maxOutputTokens": 48}}, note="grounding.py googleSearch")104print("HTTP", st)105if st != 200:106    print(json.dumps(r.get("error"), indent=1)[:600]); sys.exit(0)107cand = r["candidates"][0]108gm = cand.get("groundingMetadata", {})109print("text:", "".join(p.get("text", "") for p in cand["content"]["parts"]))110print("webSearchQueries:", gm.get("webSearchQueries"))111for i, c in enumerate(gm.get("groundingChunks", [])):112    print(f"chunk[{i}] web.title={c.get('web', {}).get('title')!r} uri={c.get('web', {}).get('uri', '')[:60]}")113for s in gm.get("groundingSupports", []):114    print("support:", s["segment"].get("text", "")[:60], "→ chunks", s.get("groundingChunkIndices"), "conf", s.get("confidenceScores"))115print("searchEntryPoint.renderedContent present:", bool(gm.get("searchEntryPoint", {}).get("renderedContent")))  # must be displayed per ToS116
Files main
Menu

Theme