Spaces:
Sleeping
Sleeping
File size: 1,626 Bytes
80ef840 | 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 | import json
import re
import httpx
from app.utils.logger import get_logger
logger = get_logger(__name__)
class GeminiClient:
def __init__(self, api_key: str | None = None, model: str = "gemini-1.5-flash"):
self.api_key = api_key
self.model = model
def validate(self, response: str, context: str) -> dict:
if not self.api_key:
logger.info("Gemini API key not configured; using local validation.")
has_policy_context = bool(context.strip())
return {
"valid": has_policy_context and len(response.strip()) > 20,
"issues": [] if has_policy_context else ["No policy context was supplied."],
}
prompt = f"""
Validate this customer support response against the policy context.
Return only JSON with keys: valid (boolean), issues (array of strings).
Policy context:
{context}
Customer response:
{response}
"""
api_response = httpx.post(
f"https://generativelanguage.googleapis.com/v1beta/models/{self.model}:generateContent",
params={"key": self.api_key},
json={"contents": [{"parts": [{"text": prompt}]}]},
timeout=45,
)
api_response.raise_for_status()
text = api_response.json()["candidates"][0]["content"]["parts"][0]["text"]
return self._parse_json(text)
def _parse_json(self, text: str) -> dict:
cleaned = text.strip()
fenced = re.search(r"```(?:json)?\s*(.*?)```", cleaned, flags=re.DOTALL)
if fenced:
cleaned = fenced.group(1).strip()
return json.loads(cleaned)
|