care_agets / utils /gemini_client.py
omgy's picture
Create utils/gemini_client.py
199597a verified
import os
import logging
try:
import google.generativeai as genai
except Exception:
genai = None
GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY")
if not GEMINI_API_KEY:
raise RuntimeError("Set GEMINI_API_KEY in environment (HF secrets).")
if genai:
genai.configure(api_key=GEMINI_API_KEY)
def ask_gemini(prompt: str, model: str = "gemini-1.5-mini", max_output_tokens: int = 256) -> str:
"""
Returns the raw string response.
If the google.generativeai package is not present or API differs, replace this
with the official call for your Gemini client library.
"""
try:
if genai:
# The library may use different function names in future.
# If this errors, replace with the library's generate_content/generate_text call.
response = genai.generate_text(model=model, prompt=prompt, max_output_tokens=max_output_tokens)
return response.text if hasattr(response, "text") else str(response)
else:
# fallback - attempt direct HTTP call (user may replace this)
import requests
url = "https://api.generativeai.googleapis.com/v1/models/{}/generate".format(model)
headers = {"Authorization": f"Bearer {GEMINI_API_KEY}", "Content-Type": "application/json"}
payload = {"prompt": prompt, "max_output_tokens": max_output_tokens}
r = requests.post(url, json=payload, headers=headers, timeout=30)
r.raise_for_status()
j = r.json()
# extract sensible text field (adjust to actual response shape)
return j.get("candidates", [{}])[0].get("content", "")
except Exception as e:
logging.exception("Gemini call failed")
return ""