File size: 5,902 Bytes
88263c8
 
 
 
 
1ed0a11
 
 
 
88263c8
 
 
1ed0a11
 
88263c8
 
1ed0a11
 
88263c8
1ed0a11
 
 
88263c8
1ed0a11
 
 
 
 
88263c8
1ed0a11
 
88263c8
1ed0a11
 
 
 
 
 
 
88263c8
1ed0a11
 
88263c8
1ed0a11
 
 
88263c8
1ed0a11
 
 
88263c8
 
1ed0a11
 
 
 
 
 
 
88263c8
 
 
1ed0a11
 
 
88263c8
 
 
 
 
 
 
 
 
 
 
 
 
1ed0a11
 
88263c8
1ed0a11
 
88263c8
1ed0a11
 
 
 
 
 
 
 
88263c8
1ed0a11
88263c8
 
1ed0a11
88263c8
1ed0a11
 
 
88263c8
 
1ed0a11
88263c8
 
1ed0a11
 
88263c8
1ed0a11
88263c8
1ed0a11
 
 
88263c8
1ed0a11
88263c8
 
 
1ed0a11
 
88263c8
1ed0a11
 
88263c8
1ed0a11
 
88263c8
1ed0a11
 
 
88263c8
1ed0a11
88263c8
 
1ed0a11
88263c8
1ed0a11
 
 
88263c8
 
1ed0a11
88263c8
1ed0a11
 
 
88263c8
1ed0a11
88263c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ed0a11
 
88263c8
 
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
"""

src/utils/base_utils.py

Shared utilities: Groq client, Gemini client, JSON cleaner, topic sampler.

No UI concerns — pure back-end helpers.

"""
import os
import json
import logging
import re
import random
from typing import Optional

from groq import Groq
import httpx

from .questions import parse_groq_response  # noqa: F401  (re-exported for callers)

# -----------------------------------------------------------
# Logging
# -----------------------------------------------------------
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)
logger = logging.getLogger(__name__)


# -----------------------------------------------------------
# Custom Exception
# -----------------------------------------------------------
class ModelError(Exception):
    """Raised when a model client fails to initialise or returns bad output."""
    pass


# -----------------------------------------------------------
# Groq Client
# -----------------------------------------------------------
def get_groq_client() -> Groq:
    """Initialise and return a Groq client."""
    api_key = os.getenv("GROQ_API_KEY")
    if not api_key:
        logger.error("GROQ_API_KEY is missing from environment variables.")
        raise ModelError("GROQ_API_KEY environment variable not set")

    try:
        # Use a plain httpx.Client to avoid proxy-parameter incompatibilities.
        http_client = httpx.Client()
        return Groq(api_key=api_key, http_client=http_client)
    except Exception as e:
        logger.error("Failed to initialise Groq client: %s", e)
        raise ModelError(f"Failed to initialise Groq client: {e}") from e


# -----------------------------------------------------------
# Gemini Client
# -----------------------------------------------------------
def get_gemini_client():
    """

    Initialise and return a Gemini 1.5 Flash generative model instance.

    Returns None (with a logged error) if the package is missing or the

    API key is not set — callers should handle the None case gracefully.

    """
    try:
        import google.generativeai as genai
    except ImportError:
        logger.error(
            "google-generativeai is not installed. "
            "Run: pip install google-generativeai"
        )
        return None

    api_key = os.getenv("GEMINI_API_KEY")
    if not api_key:
        logger.error("GEMINI_API_KEY not found in environment.")
        return None

    try:
        genai.configure(api_key=api_key)
        model = genai.GenerativeModel("gemini-1.5-flash")
        logger.info("Gemini 1.5 Flash client initialised.")
        return model
    except Exception as e:
        logger.error("Failed to initialise Gemini client: %s", e)
        return None


# -----------------------------------------------------------
# JSON Cleaning Utility
# -----------------------------------------------------------
def clean_json_content(content: str) -> str:
    """

    Attempt to repair and normalise LLM-produced JSON.



    Returns a valid JSON string (output of json.dumps) or raises

    ModelError if the content cannot be salvaged.

    """
    original = content

    try:
        content = content.strip()

        # Strip code fences
        content = re.sub(r"^```json", "", content, flags=re.IGNORECASE)
        content = re.sub(r"^```",     "", content)
        content = re.sub(r"```$",     "", content)
        content = content.strip()

        # Quick parse — succeeds for well-formed output
        try:
            return json.dumps(json.loads(content))
        except json.JSONDecodeError:
            pass

        # Normalise curly / smart quotes
        content = (
            content
            .replace("\u201c", '"').replace("\u201d", '"')
            .replace("\u2018", "'").replace("\u2019", "'")
        )

        # Single → double quotes (blunt but usually effective for LLM output)
        content = re.sub(r"'", '"', content)

        # Strip trailing commas before ] or }
        content = re.sub(r",\s*([}\]])", r"\1", content)

        # Ensure outermost braces
        if not content.startswith("{"):
            content = "{" + content
        if not content.endswith("}"):
            content += "}"

        # Collapse excess whitespace
        content = re.sub(r"\s+", " ", content)

        return json.dumps(json.loads(content))

    except Exception as e:
        logger.error(
            "JSON cleaning failed: %s\nOriginal:\n%s\nAfter cleaning:\n%s",
            e, original, content,
        )
        raise ModelError(f"Failed to clean JSON content: {e}") from e


# -----------------------------------------------------------
# Topic Sampler
# -----------------------------------------------------------
_TOPICS = [
    # Academic / general
    "environmental conservation",
    "digital technology",
    "global education",
    "public health",
    "cultural diversity",
    "urban development",
    "scientific research",
    "economic growth",
    "social media impact",
    "renewable energy",
    "artificial intelligence",
    "climate change",
    "online learning",
    "transportation systems",
    "workplace communication",
    "international trade",
    "mental wellbeing",
    "sustainable living",
    "innovation trends",
    "community development",
    # Additional variety
    "technology and innovation",
    "health and wellness",
    "education systems",
    "space exploration",
    "cultural heritage",
    "modern transportation",
    "digital communication",
    "scientific discoveries",
    "global economics",
]


def get_random_topic() -> str:
    """Return a random academic topic string."""
    return random.choice(_TOPICS)