""" Shared LLM helper utilities used by both agent nodes and guardrails. """ import json import logging from langchain_openai import ChatOpenAI from app.config import settings logger = logging.getLogger(__name__) def get_llm(temperature: float = 1.0, model: str = None) -> ChatOpenAI: """Create a ChatOpenAI instance with standard ACPC Chatbot headers.""" # Set this to True to test using the Groq API key and settings provided # Set to False to use the standard OpenRouter .env configuration USE_GROQ_TESTING = False if USE_GROQ_TESTING: return ChatOpenAI( model="openai/gpt-oss-120b", api_key="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", base_url="https://api.groq.com/openai/v1", temperature=1.0, max_completion_tokens=2048, # Reduced from 8192 to fit within the 8000 TPM limit top_p=1, reasoning_effort="medium", default_headers={ "HTTP-Referer": "https://acpc.gujarat.gov.in", "X-Title": "ACPC Chatbot", }, ) else: return ChatOpenAI( model=model or settings.llm_model, api_key=settings.openai_api_key, base_url=settings.openai_api_base, temperature=temperature, reasoning_effort="medium", max_tokens=2048, default_headers={ "HTTP-Referer": "https://acpc.gujarat.gov.in", "X-Title": "ACPC Chatbot", }, ) def safe_parse_json(content: str, default_key: str = None) -> dict: """Safely parse JSON response with fallback handling.""" try: result = json.loads(content.strip()) if not isinstance(result, dict): logger.warning("JSON response is not a dict: %s", type(result)) return {} if default_key is None else {default_key: None} return result except json.JSONDecodeError as e: logger.warning("JSON parse error: %s on content: %s", e, content[:100]) return {} if default_key is None else {default_key: None}