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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
398
"""
agents.py β€” Multi-provider agent runner with health checking, fallback, and vision support.

Supported providers:
  anthropic   β€” Claude (vision-capable)
  groq        β€” Groq free tier (text only)
  nvidia      β€” NVIDIA NIM ($200 free credits, auto-fallback across models)
  huggingface β€” HuggingFace Inference API
  kimi        β€” Moonshot AI / Kimi
  openai      β€” OpenAI (vision-capable)
  custom      β€” Any OpenAI-compatible endpoint

NVIDIA behaviour: on startup a background thread pings all NVIDIA models in parallel.
When a build runs, run_agent_with_fallback() tries healthy models first and automatically
falls back to the next model (or to Groq) if any call fails.
"""

import os
import time
import threading
from typing import Optional


# ── Provider base URLs ────────────────────────────────────────────────────────

PROVIDER_DEFAULTS = {
    "groq":        "https://api.groq.com/openai/v1",
    "nvidia":      "https://integrate.api.nvidia.com/v1",
    "huggingface": "https://api-inference.huggingface.co/v1",
    "kimi":        "https://api.moonshot.cn/v1",
    "openai":      None,
    "together":    "https://api.together.xyz/v1",
    "mistral":     "https://api.mistral.ai/v1",
}

PROVIDER_KEY_ENVS = {
    "anthropic":   "ANTHROPIC_API_KEY",
    "groq":        "GROQ_API_KEY",
    "nvidia":      "NVIDIA_API_KEY",
    "huggingface": "HF_TOKEN",
    "kimi":        "MOONSHOT_API_KEY",
    "openai":      "OPENAI_API_KEY",
    "together":    "TOGETHER_API_KEY",
    "mistral":     "MISTRAL_API_KEY",
    "custom":      "CUSTOM_API_KEY",
}

# ── NVIDIA model priority lists ───────────────────────────────────────────────

NVIDIA_TEXT_MODELS = [
    "meta/llama-3.3-70b-instruct",
    "nvidia/llama-3.1-nemotron-70b-instruct",
    "meta/llama-3.1-70b-instruct",
    "mistralai/mixtral-8x7b-instruct-v0.1",
    "microsoft/phi-3-medium-128k-instruct",
    "meta/llama-3.1-8b-instruct",
]

NVIDIA_CODE_MODELS = [
    "qwen/qwen2.5-coder-32b-instruct",
    "meta/llama-3.3-70b-instruct",
    "nvidia/llama-3.1-nemotron-70b-instruct",
    "mistralai/mixtral-8x7b-instruct-v0.1",
    "meta/llama-3.1-8b-instruct",
]

NVIDIA_VISION_MODELS = [
    "meta/llama-3.2-90b-vision-instruct",
    "meta/llama-3.2-11b-vision-instruct",
    "microsoft/phi-3-vision-128k-instruct",
]

# Models that accept image inputs
VISION_CAPABLE = set(NVIDIA_VISION_MODELS) | {
    "claude-sonnet-4-6", "claude-opus-4-6", "claude-haiku-4-5-20251001",
    "gpt-4o", "gpt-4o-mini", "gpt-4-turbo",
}

# ── Health check state ────────────────────────────────────────────────────────

_health: dict[str, bool] = {}        # {model_name: is_alive}
_health_lock = threading.Lock()
_health_done = False                  # True once a full check has completed
_health_in_progress = False


def _ping_model(model: str, api_key: str, base_url: str, results: dict, timeout: int = 12):
    """Worker: ping one model and store True/False in results dict."""
    try:
        import openai
        client = openai.OpenAI(api_key=api_key, base_url=base_url, timeout=timeout)
        client.chat.completions.create(
            model=model,
            messages=[{"role": "user", "content": "Hi"}],
            max_tokens=3,
        )
        results[model] = True
    except Exception:
        results[model] = False


def run_nvidia_health_check(api_key: str = "", force: bool = False) -> dict[str, bool]:
    """
    Ping all NVIDIA models in parallel (up to 20s).
    Returns {model: is_alive}. Results cached for the session; pass force=True to re-check.
    """
    global _health, _health_done, _health_in_progress

    key = api_key or os.environ.get("NVIDIA_API_KEY", "")
    if not key:
        return {}

    with _health_lock:
        if _health_done and not force:
            return dict(_health)
        if _health_in_progress:
            return dict(_health)
        _health_in_progress = True

    all_models = list(dict.fromkeys(
        NVIDIA_TEXT_MODELS + NVIDIA_CODE_MODELS + NVIDIA_VISION_MODELS
    ))

    results: dict[str, bool] = {}
    threads = [
        threading.Thread(
            target=_ping_model,
            args=(m, key, "https://integrate.api.nvidia.com/v1", results),
            daemon=True,
        )
        for m in all_models
    ]
    for t in threads:
        t.start()
    for t in threads:
        t.join(timeout=22)

    with _health_lock:
        _health = results
        _health_done = True
        _health_in_progress = False

    return dict(results)


def reset_health_cache():
    """Clear cached results so the next call re-checks."""
    global _health_done
    with _health_lock:
        _health.clear()
        _health_done = False


def get_health_summary() -> str:
    """Return a markdown table of NVIDIA model health status."""
    with _health_lock:
        if not _health:
            return "*No health check run yet. Click **Check NVIDIA Models** above.*"
        lines = ["| Model | Status |", "|-------|--------|"]
        for model in NVIDIA_TEXT_MODELS + NVIDIA_CODE_MODELS + NVIDIA_VISION_MODELS:
            if model in _health:
                icon = "βœ… Live" if _health[model] else "❌ Down"
                category = (
                    "🎨 Vision" if model in NVIDIA_VISION_MODELS
                    else "πŸ”¨ Code" if model in NVIDIA_CODE_MODELS
                    else "🧠 Text"
                )
                lines.append(f"| `{model}` | {category} Β· {icon} |")
        alive = sum(_health.values())
        lines.append(f"\n**{alive}/{len(_health)} models responding**")
        return "\n".join(lines)


def get_best_nvidia_model(kind: str = "text") -> str:
    """Return the first live NVIDIA model for the given kind (text/code/vision)."""
    candidates = (
        NVIDIA_CODE_MODELS if kind == "code"
        else NVIDIA_VISION_MODELS if kind == "vision"
        else NVIDIA_TEXT_MODELS
    )
    with _health_lock:
        for m in candidates:
            if _health.get(m, True):   # assume alive if unchecked
                return m
    return candidates[0]


# ── Internal helpers ──────────────────────────────────────────────────────────

def _get_api_key(agent_config: dict) -> str:
    provider = agent_config.get("provider", "anthropic")
    env_var = agent_config.get("api_key_env") or PROVIDER_KEY_ENVS.get(provider, "API_KEY")
    key = os.environ.get(env_var, "")
    if not key:
        raise EnvironmentError(
            f"API key not found. Set '{env_var}' for the '{provider}' provider."
        )
    return key


def _encode_image(image_input) -> Optional[str]:
    """Convert a PIL Image or numpy array to base64 JPEG. Returns None on failure."""
    if image_input is None:
        return None
    try:
        import io as _io
        import base64 as _b64
        from PIL import Image as PILImage

        if not isinstance(image_input, PILImage.Image):
            img = PILImage.fromarray(image_input)
        else:
            img = image_input

        buf = _io.BytesIO()
        img.convert("RGB").save(buf, format="JPEG", quality=90)
        return _b64.b64encode(buf.getvalue()).decode()
    except Exception:
        return None


def _call_anthropic(
    agent_config: dict,
    user_input: str,
    image_b64: Optional[str] = None,
) -> tuple[str, int, int]:
    import anthropic

    key = _get_api_key(agent_config)
    client = anthropic.Anthropic(api_key=key)
    model = agent_config["model"]

    if image_b64 and model in VISION_CAPABLE:
        content = [
            {
                "type": "image",
                "source": {"type": "base64", "media_type": "image/jpeg", "data": image_b64},
            },
            {"type": "text", "text": user_input},
        ]
    else:
        content = user_input

    response = client.messages.create(
        model=model,
        max_tokens=agent_config.get("max_tokens", 4096),
        temperature=agent_config.get("temperature", 0.7),
        system=agent_config["system_prompt"].strip(),
        messages=[{"role": "user", "content": content}],
    )
    text = response.content[0].text
    return text, response.usage.input_tokens, response.usage.output_tokens


def _call_openai_compat(
    agent_config: dict,
    user_input: str,
    image_b64: Optional[str] = None,
) -> tuple[str, int, int]:
    import openai

    provider = agent_config.get("provider", "openai")
    key = _get_api_key(agent_config)
    base_url = agent_config.get("base_url") or PROVIDER_DEFAULTS.get(provider)
    model = agent_config["model"]

    client = openai.OpenAI(api_key=key, base_url=base_url)

    if image_b64 and model in VISION_CAPABLE:
        user_content = [
            {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{image_b64}"}},
            {"type": "text", "text": user_input},
        ]
    else:
        user_content = user_input

    response = client.chat.completions.create(
        model=model,
        max_tokens=agent_config.get("max_tokens", 4096),
        temperature=agent_config.get("temperature", 0.7),
        messages=[
            {"role": "system", "content": agent_config["system_prompt"].strip()},
            {"role": "user",   "content": user_content},
        ],
    )
    content = response.choices[0].message.content or ""
    usage = response.usage
    return content, (usage.prompt_tokens if usage else 0), (usage.completion_tokens if usage else 0)


# ── Public API ────────────────────────────────────────────────────────────────

def run_agent(
    agent_config: dict,
    model: Optional[str],
    user_input: str,
    stage: str,
    verbose: bool = True,
    image_b64: Optional[str] = None,
) -> dict:
    """Run a single agent call. Raises RuntimeError on failure."""
    provider = agent_config.get("provider", "anthropic")
    effective_model = agent_config.get("model") or model or "claude-sonnet-4-6"
    agent_config = {**agent_config, "model": effective_model}

    if verbose:
        print(f"  β†’ [{provider.upper()}] {agent_config['name']} ({effective_model})...")

    start = time.time()
    try:
        if provider == "anthropic":
            content, in_tok, out_tok = _call_anthropic(agent_config, user_input, image_b64)
        else:
            content, in_tok, out_tok = _call_openai_compat(agent_config, user_input, image_b64)
    except Exception as e:
        raise RuntimeError(f"Agent '{agent_config['name']}' ({provider}) failed: {e}") from e

    duration = round(time.time() - start, 2)
    if verbose:
        total = in_tok + out_tok
        print(f"  βœ“ {agent_config['name']} done ({total:,} tokens, {duration}s)")

    return {
        "stage":         stage,
        "agent_name":    agent_config["name"],
        "provider":      provider,
        "model":         effective_model,
        "content":       content,
        "input_tokens":  in_tok,
        "output_tokens": out_tok,
        "duration_s":    duration,
    }


def run_agent_with_fallback(
    agent_config: dict,
    user_input: str,
    stage: str,
    image_b64: Optional[str] = None,
    verbose: bool = True,
) -> dict:
    """
    Run an agent with automatic NVIDIA model fallback.

    For non-NVIDIA providers, behaves identically to run_agent().
    For NVIDIA:
      1. Tries healthy models first (from cached health check).
      2. On failure, tries the next model in priority order.
      3. If all NVIDIA models fail, falls back to Groq llama-3.3-70b-versatile.
      4. If Groq key is absent too, raises a RuntimeError with a clear message.
    """
    provider = agent_config.get("provider", "groq")

    if provider != "nvidia":
        return run_agent(agent_config, None, user_input, stage, verbose, image_b64)

    # Pick candidate list based on stage and whether an image is attached
    if image_b64:
        candidates = NVIDIA_VISION_MODELS + (NVIDIA_CODE_MODELS if stage == "builder" else NVIDIA_TEXT_MODELS)
    elif stage == "builder":
        candidates = NVIDIA_CODE_MODELS
    else:
        candidates = NVIDIA_TEXT_MODELS

    # Sort: healthy first, then unchecked, then known-bad
    with _health_lock:
        healthy   = [m for m in candidates if _health.get(m) is True]
        unchecked = [m for m in candidates if m not in _health]
        unhealthy = [m for m in candidates if _health.get(m) is False]
    priority = healthy + unchecked + unhealthy

    last_err = None
    for model in priority[:5]:
        try:
            cfg = {**agent_config, "model": model}
            result = run_agent(cfg, None, user_input, stage, verbose, image_b64)
            with _health_lock:
                _health[model] = True
            return result
        except Exception as e:
            last_err = e
            with _health_lock:
                _health[model] = False
            if verbose:
                print(f"  ⚠ {model} failed ({e}), trying next NVIDIA model...")
            continue

    groq_key = os.environ.get("GROQ_API_KEY", "")
    if groq_key:
        if verbose:
            print("  ⚠ All NVIDIA models failed. Falling back to Groq llama-3.3-70b-versatile...")
        cfg = {**agent_config, "provider": "groq", "model": "llama-3.3-70b-versatile"}
        return run_agent(cfg, None, user_input, stage, verbose, image_b64)

    raise RuntimeError(
        f"All NVIDIA models failed and GROQ_API_KEY is not set. Last error: {last_err}"
    )