atlas / gemini_client.py
ANISA09's picture
Create gemini_client.py
5952ab9 verified
# gemini_client.py
import os
import json
import logging
from typing import Dict, Any
try:
from google import genai
except Exception:
genai = None
logger = logging.getLogger("gemini_client")
GENAI_MODEL = os.getenv("GENAI_MODEL", "gemini-2.5-flash")
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
genai_client = None
if genai:
try:
genai_client = genai.Client(api_key=GEMINI_API_KEY) if GEMINI_API_KEY else genai.Client()
logger.info("Gemini client initialized")
except Exception as e:
logger.warning("Could not initialize genai client: %s", e)
genai_client = None
else:
logger.info("genai not available; Gemini disabled")
def _extract_json_from_text(text: str):
# simple JSON extractor re-used from original script
if not text:
return None
start = None
depth = 0
for i, ch in enumerate(text):
if ch == "{":
if start is None:
start = i
depth += 1
elif ch == "}":
if depth > 0:
depth -= 1
if depth == 0 and start is not None:
return text[start:i+1]
return None
def call_gemini_synthesizer(claim: str, article_text: str, tools_outputs: Dict[str, Any]) -> Dict[str, Any]:
if not genai_client:
return {"error": "Gemini not configured"}
tools_snapshot = json.dumps(tools_outputs, indent=0)[:15000]
prompt = f"""
You are an expert fact-checker. Based on these tool outputs (JSON) and the claim, return JSON:
{{"verdict":"True|False|Misleading|Unclear","score":1..10,"explanation":"...","issues":[],"recommendations":[]}}
Tool outputs:
{tools_snapshot}
Claim:
{claim}
Article:
{article_text}
Return JSON only.
"""
try:
resp = genai_client.models.generate_content(model=GENAI_MODEL, contents=prompt)
raw = getattr(resp, "text", None) or str(resp)
maybe = _extract_json_from_text(raw)
if maybe:
parsed = json.loads(maybe)
return {"raw": raw, "parsed": parsed}
return {"raw": raw, "error": "No JSON in response"}
except Exception as e:
logger.exception("call_gemini_synthesizer failed")
return {"error": str(e)}