File size: 15,194 Bytes
186efee
 
 
 
 
 
 
 
 
950dcd2
 
 
 
 
 
 
 
 
 
 
186efee
950dcd2
186efee
 
950dcd2
 
 
 
 
7e6a5ea
950dcd2
 
 
 
 
 
 
7e6a5ea
186efee
 
 
 
 
 
 
 
 
 
 
 
 
7e6a5ea
186efee
 
 
 
 
 
7e6a5ea
186efee
 
 
 
 
 
7e6a5ea
186efee
 
 
 
 
009e621
 
 
 
186efee
 
 
 
 
 
 
 
 
950dcd2
186efee
 
 
 
 
950dcd2
186efee
 
 
950dcd2
186efee
 
 
950dcd2
 
 
 
 
 
 
 
 
 
 
 
186efee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85a09fa
 
186efee
 
 
 
 
950dcd2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
186efee
85a09fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
186efee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
950dcd2
186efee
 
 
 
 
950dcd2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
186efee
950dcd2
 
 
 
 
186efee
 
 
 
 
950dcd2
186efee
950dcd2
186efee
 
 
85a09fa
 
950dcd2
 
 
 
 
 
85a09fa
950dcd2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
186efee
 
 
950dcd2
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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
"""Multi-provider AI engine with smart task routing.

Runtime chain: Groq -> Cerebras -> OpenRouter -> Mistral -> Ollama.
Task hints route to the best model for the job:
  - "arabic"   β†’ large models (70B+) for Arabic NLP quality
  - "code"     β†’ code-optimized models
  - "fast"     β†’ smallest/fastest model available
  - "default"  β†’ standard free-tier chain
"""
import json, logging, os, re, requests

logger = logging.getLogger(__name__)
_OLLAMA_BASE = "http://localhost:11434"

_PROVIDER_URLS = {
    "groq":       "https://api.groq.com/openai/v1/chat/completions",
    "cerebras":   "https://api.cerebras.ai/v1/chat/completions",
    "openrouter": "https://openrouter.ai/api/v1/chat/completions",
    "mistral":    "https://api.mistral.ai/v1/chat/completions",
    "openai":     "https://api.openai.com/v1/chat/completions",
    "cohere":     "https://api.cohere.com/v2/chat",
}

# ── Model tiers per provider ──
_FREE_MODELS = {
    "groq":       "llama-3.1-8b-instant",
    "cerebras":   "llama3.1-8b",
    "openrouter": "google/gemma-3-12b-it:free",
    "mistral":    "mistral-small-latest",
    "cohere":     "command-r-08-2024",
}
_PREMIUM_MODELS = {
    "groq":       "llama-3.3-70b-versatile",
    "cerebras":   "qwen-3-235b-a22b-instruct-2507",
    "openrouter": "google/gemma-3-27b-it:free",
    "mistral":    "mistral-medium-latest",
    "openai":     "gpt-4o-mini",
    "cohere":     "command-r-08-2024",
}

# ── Task-specific model routing ──
# Maps task hints to the best model per provider.
# "arabic" needs large models for Arabic morphology, grammar, dialect awareness.
# "code" needs code-tuned models for test generation, SQL, schema analysis.
# "fast" uses smallest models for quick responses.
_TASK_MODELS = {
    "arabic": {
        "groq":       "llama-3.3-70b-versatile",
        "cerebras":   "qwen-3-235b-a22b-instruct-2507",
        "openrouter": "google/gemma-3-27b-it:free",
        "mistral":    "mistral-medium-latest",
        "cohere":     "command-r7b-arabic-02-2025",
    },
    "code": {
        "groq":       "llama-3.3-70b-versatile",
        "cerebras":   "qwen-3-235b-a22b-instruct-2507",
        "openrouter": "google/gemma-3-27b-it:free",
        "mistral":    "mistral-medium-latest",
        "cohere":     "command-r-08-2024",
    },
    "fast": {
        "groq":       "llama-3.1-8b-instant",
        "cerebras":   "llama3.1-8b",
        "openrouter": "google/gemma-3-12b-it:free",
        "mistral":    "mistral-small-latest",
        "cohere":     "command-r-08-2024",
    },
}

# ── Task-specific provider priority ──
_TASK_PRIORITY = {
    "arabic":  ["cerebras", "groq", "openrouter", "cohere", "mistral"],
    "code":    ["groq", "cerebras", "openrouter", "cohere", "mistral"],
    "fast":    ["cerebras", "groq", "openrouter", "cohere", "mistral"],
    "default": ["groq", "cerebras", "openrouter", "cohere", "mistral"],
}

_CHAIN_CFG = {
    "groq":       {"key_env": "GROQ_API_KEY",       "timeout": 30, "extra": {}},
    "cerebras":   {"key_env": "CEREBRAS_API_KEY",   "timeout": 30, "extra": {}},
    "openrouter": {"key_env": "OPENROUTER_API_KEY", "timeout": 45,
                   "extra": {"HTTP-Referer": "https://github.com/Moealsarraj", "X-Title": "AI Tools"}},
    "mistral":    {"key_env": "MISTRAL_API_KEY",    "timeout": 40, "extra": {}},
    "cohere":     {"key_env": "COHERE_API_KEY",     "timeout": 45, "extra": {}},
}

# Build available providers (those with valid keys)
_AVAILABLE = {}
for _name, _cfg in _CHAIN_CFG.items():
    _k = os.environ.get(_cfg["key_env"], "")
    if _k:
        _AVAILABLE[_name] = {
            "name":    _name,
            "url":     _PROVIDER_URLS[_name],
            "key":     _k,
            "timeout": _cfg["timeout"],
            "extra":   _cfg["extra"],
        }

# Ollama fallback
_OLLAMA_PROVIDER = None
try:
    _r = requests.get(f"{_OLLAMA_BASE}/api/tags", timeout=3)
    if _r.status_code == 200:
        _installed = [m["name"] for m in _r.json().get("models", [])]
        if _installed:
            _OLLAMA_PROVIDER = {"name": "ollama", "model": _installed[0]}
except Exception:
    pass

# ── Google Gemini (special API format) ──
_GEMINI_KEY = os.environ.get("GEMINI_API_KEY", "")
if _GEMINI_KEY:
    _AVAILABLE["gemini"] = {
        "name": "gemini",
        "url": "https://generativelanguage.googleapis.com/v1beta/models",
        "key": _GEMINI_KEY,
        "timeout": 60,
        "extra": {},
    }
    _FREE_MODELS["gemini"] = "gemini-2.0-flash"
    _PREMIUM_MODELS["gemini"] = "gemini-2.0-flash"
    for task in _TASK_MODELS:
        _TASK_MODELS[task]["gemini"] = "gemini-2.0-flash"
    for task in _TASK_PRIORITY:
        if "gemini" not in _TASK_PRIORITY[task]:
            _TASK_PRIORITY[task].insert(2, "gemini")

_AI_AVAILABLE = bool(_AVAILABLE or _OLLAMA_PROVIDER)


def _post_gemini(key: str, model: str, messages: list, max_tokens: int, timeout: int = 60) -> str:
    """Call Google Gemini API (non-OpenAI format)."""
    # Convert OpenAI message format to Gemini format
    contents = []
    system_text = ""
    for msg in messages:
        role = msg["role"]
        if role == "system":
            system_text = msg["content"]
            continue
        contents.append({
            "role": "user" if role == "user" else "model",
            "parts": [{"text": msg["content"]}],
        })

    body = {
        "contents": contents,
        "generationConfig": {"maxOutputTokens": max_tokens},
    }
    if system_text:
        body["systemInstruction"] = {"parts": [{"text": system_text}]}

    url = f"https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent?key={key}"
    r = requests.post(url, json=body, timeout=timeout)
    r.raise_for_status()
    data = r.json()
    return _clean(data["candidates"][0]["content"]["parts"][0]["text"])


def get_available_providers() -> list[dict]:
    """Return list of available providers with their model info."""
    providers = []
    for name, prov in _AVAILABLE.items():
        providers.append({
            "name": name,
            "model_free": _FREE_MODELS.get(name, ""),
            "model_premium": _PREMIUM_MODELS.get(name, ""),
        })
    return providers


def call_ai_single(provider_name: str, messages: list, system: str = "",
                   max_tokens: int = 2048, use_premium: bool = True) -> str:
    """Call a specific provider directly (no fallback chain)."""
    if provider_name not in _AVAILABLE:
        raise ValueError(f"Provider {provider_name!r} not available")
    prov = _AVAILABLE[provider_name]
    models = _PREMIUM_MODELS if use_premium else _FREE_MODELS
    model = models.get(provider_name, prov.get("model", ""))
    if system:
        messages = [{"role": "system", "content": system}] + messages
    if provider_name == "gemini":
        return _post_gemini(prov["key"], model, messages, max_tokens, prov["timeout"])
    if provider_name == "cohere":
        return _post_cohere(prov["key"], model, messages, max_tokens, prov["timeout"])
    return _post_openai(
        prov["url"], prov["key"], model,
        messages, max_tokens, prov["extra"], prov["timeout"]
    )


_RE_THINK = re.compile(r"<think>.*?</think>", re.DOTALL)
_RE_OPEN  = re.compile(r"^```[a-z]*\n?", re.MULTILINE)
_RE_CLOSE = re.compile(r"\n?```$", re.MULTILINE)

def _clean(raw: str) -> str:
    raw = _RE_THINK.sub("", raw).strip()
    raw = _RE_OPEN.sub("", raw)
    return _RE_CLOSE.sub("", raw).strip()

def _post_openai(url, key, model, messages, max_tokens, extra_headers, timeout=60):
    headers = {"Authorization": f"Bearer {key}", "Content-Type": "application/json"}
    headers.update(extra_headers)
    r = requests.post(url, headers=headers,
        json={"model": model, "messages": messages, "max_tokens": max_tokens},
        timeout=timeout)
    r.raise_for_status()
    return _clean(r.json()["choices"][0]["message"]["content"])


def _post_cohere(key: str, model: str, messages: list, max_tokens: int, timeout: int = 45) -> str:
    """Call Cohere V2 Chat API."""
    headers = {"Authorization": f"Bearer {key}", "Content-Type": "application/json"}
    r = requests.post("https://api.cohere.com/v2/chat",
        headers=headers,
        json={"model": model, "messages": messages, "max_tokens": max_tokens},
        timeout=timeout)
    r.raise_for_status()
    data = r.json()
    # V2 returns content as list of blocks
    content = data.get("message", {}).get("content", [])
    if content and isinstance(content, list):
        return _clean(content[0].get("text", ""))
    return _clean(str(data))


def _build_chain(task_hint: str) -> list[dict]:
    """Build an ordered provider chain for the given task hint."""
    hint = task_hint if task_hint in _TASK_PRIORITY else "default"
    priority = _TASK_PRIORITY[hint]
    models = _TASK_MODELS.get(hint, _FREE_MODELS)

    chain = []
    for name in priority:
        if name in _AVAILABLE:
            prov = _AVAILABLE[name].copy()
            prov["model"] = models.get(name, _FREE_MODELS.get(name, ""))
            chain.append(prov)
    return chain


def call_ai(messages: list, system: str = "", max_tokens: int = 2048,
            api_key_row: dict | None = None, task_hint: str = "default") -> str:
    """Call AI with smart task-based routing.

    task_hint: "arabic" | "code" | "fast" | "default"
    """
    if system:
        messages = [{"role": "system", "content": system}] + messages
    # Custom API key path (used by e.g. Wasit/Amin integrations)
    if api_key_row:
        provider = api_key_row.get("provider", "openai")
        key      = api_key_row["key"]
        url      = api_key_row.get("url") or _PROVIDER_URLS.get(provider, "")
        model    = api_key_row.get("model") or _PREMIUM_MODELS.get(provider, "gpt-4o-mini")
        if not url:
            raise ValueError(f"No endpoint known for provider {provider!r}")
        if provider == "claude":
            r = requests.post("https://api.anthropic.com/v1/messages",
                headers={"x-api-key": key, "anthropic-version": "2023-06-01",
                         "content-type": "application/json"},
                json={"model": "claude-sonnet-4-6", "max_tokens": max_tokens, "messages": messages},
                timeout=60)
            r.raise_for_status()
            return _clean(r.json()["content"][0]["text"])
        return _post_openai(url, key, model, messages, max_tokens, {})
    if not _AI_AVAILABLE:
        raise RuntimeError("No AI provider. Set GROQ_API_KEY or similar in .env")
    # Ollama-only path
    if not _AVAILABLE and _OLLAMA_PROVIDER:
        r = requests.post(f"{_OLLAMA_BASE}/api/chat",
            json={"model": _OLLAMA_PROVIDER["model"], "messages": messages, "stream": False},
            timeout=120)
        r.raise_for_status()
        return _clean(r.json()["message"]["content"])
    # Smart task-routed chain
    chain = _build_chain(task_hint)
    if not chain:
        chain = _build_chain("default")

    last_exc = None
    for prov in chain:
        try:
            logger.debug("Trying %s/%s for task=%s", prov["name"], prov["model"], task_hint)
            if prov["name"] == "gemini":
                return _post_gemini(prov["key"], prov["model"], messages, max_tokens, prov["timeout"])
            if prov["name"] == "cohere":
                return _post_cohere(prov["key"], prov["model"], messages, max_tokens, prov["timeout"])
            return _post_openai(
                prov["url"], prov["key"], prov["model"],
                messages, max_tokens, prov["extra"], prov["timeout"]
            )
        except requests.exceptions.HTTPError as e:
            status = e.response.status_code if e.response is not None else 0
            if status in (402, 429, 503, 502):
                logger.debug("Provider %s returned %s, trying next", prov["name"], status)
                last_exc = e
                continue
            raise
        except (requests.exceptions.ConnectionError,
                requests.exceptions.Timeout) as e:
            last_exc = e
            continue
    # Try Ollama as last resort
    if _OLLAMA_PROVIDER:
        r = requests.post(f"{_OLLAMA_BASE}/api/chat",
            json={"model": _OLLAMA_PROVIDER["model"], "messages": messages, "stream": False},
            timeout=120)
        r.raise_for_status()
        return _clean(r.json()["message"]["content"])
    raise last_exc or RuntimeError("All AI providers failed or rate-limited")

def _repair_json(text: str) -> str:
    """Escape literal control characters inside JSON string values."""
    result = []
    in_str = False
    esc = False
    for c in text:
        if esc:
            result.append(c)
            esc = False
            continue
        if c == '\\' and in_str:
            result.append(c)
            esc = True
            continue
        if c == '"':
            in_str = not in_str
            result.append(c)
            continue
        if in_str and c == '\n':
            result.append('\\n')
            continue
        if in_str and c == '\r':
            result.append('\\r')
            continue
        if in_str and c == '\t':
            result.append('\\t')
            continue
        result.append(c)
    return ''.join(result)

def _extract_json(raw: str):
    """Try progressively harder to extract valid JSON from raw text."""
    raw = raw.strip()
    # Direct parse
    try:
        return json.loads(raw)
    except json.JSONDecodeError:
        pass
    # Repair literal newlines inside strings then retry
    repaired = _repair_json(raw)
    try:
        return json.loads(repaired)
    except json.JSONDecodeError:
        pass
    # Find first { or [ then walk to find matching closer
    for source in (repaired, raw):
        for start_ch, end_ch in [('{', '}'), ('[', ']')]:
            idx = source.find(start_ch)
            if idx == -1:
                continue
            depth = 0
            in_str = False
            esc = False
            for i in range(idx, len(source)):
                c = source[i]
                if esc:
                    esc = False
                    continue
                if c == '\\' and in_str:
                    esc = True
                    continue
                if c == '"':
                    in_str = not in_str
                    continue
                if in_str:
                    continue
                if c == start_ch:
                    depth += 1
                elif c == end_ch:
                    depth -= 1
                    if depth == 0:
                        candidate = source[idx:i+1]
                        try:
                            return json.loads(candidate)
                        except json.JSONDecodeError:
                            break
    raise ValueError(f"AI returned non-JSON: {raw[:200]}")

def call_ai_json(messages: list, system: str = "", max_tokens: int = 2048,
                 api_key_row: dict | None = None, task_hint: str = "default") -> dict | list:
    raw = call_ai(messages, system=system, max_tokens=max_tokens,
                  api_key_row=api_key_row, task_hint=task_hint)
    return _extract_json(raw)