-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgrounding_search.py
More file actions
95 lines (77 loc) · 2.88 KB
/
grounding_search.py
File metadata and controls
95 lines (77 loc) · 2.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import os
import sys
import logging
import time
from typing import Optional
from dotenv import load_dotenv
from google import genai
from google.genai import types
load_dotenv('.env.local') # Load environment variables from .env.local
def setup_logging() -> None:
"""Set up basic logging configuration."""
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(levelname)s - %(message)s"
)
def get_grounding_response(query: str, max_retries: int = 3) -> Optional[str]:
"""
Generate content using Gemini with Google Search grounding.
Args:
query: The query string to process.
max_retries: Maximum number of retries for transient errors.
Returns:
The generated response text, or None if an error occurs.
"""
for attempt in range(max_retries + 1):
try:
# Initialize the client (assumes GOOGLE_API_KEY is set in environment)
client = genai.Client()
# Define the grounding tool
grounding_tool = types.Tool(google_search=types.GoogleSearch())
# Configure the generation settings
config = types.GenerateContentConfig(tools=[grounding_tool])
# Generate content
response = client.models.generate_content(
model="gemini-2.5-flash",
contents=query,
config=config,
)
return response.text
except Exception as e:
error_message = str(e)
if "503" in error_message or "UNAVAILABLE" in error_message:
if attempt < max_retries:
wait_time = 2 ** attempt # Exponential backoff
logging.warning(f"Service unavailable, retrying in {wait_time} seconds... (attempt {attempt + 1}/{max_retries + 1})")
time.sleep(wait_time)
continue
logging.error(f"An error occurred while generating content: {e}")
return None
return None
def main() -> None:
"""Main function to handle user input and generate response."""
setup_logging()
# Check for API key
api_key = os.getenv("GEMINI_API_KEY")
if not api_key:
logging.error("GEMINI_API_KEY environment variable is not set.")
sys.exit(1)
# Set GOOGLE_API_KEY for the library
os.environ["GOOGLE_API_KEY"] = api_key
# Get query from command line argument or prompt
if len(sys.argv) > 1:
query = " ".join(sys.argv[1:])
else:
query = input("Enter your query: ").strip()
if not query:
logging.error("No query provided.")
sys.exit(1)
logging.info(f"Processing query: {query}")
# Get and print the response
response = get_grounding_response(query)
if response:
print(response)
else:
logging.error("Failed to generate response.")
if __name__ == "__main__":
main()