sanelyhusen commited on
Commit
5cd48c5
Β·
verified Β·
1 Parent(s): 407c03d

Update agents.py

Browse files
Files changed (1) hide show
  1. agents.py +293 -71
agents.py CHANGED
@@ -1,38 +1,38 @@
1
  """
2
- agents.py β€” Multi-provider agent runner.
3
-
4
- Supported providers (set per-agent in config.yaml):
5
- anthropic β€” Anthropic Claude (claude-sonnet-4-6, claude-opus-4-6, etc.)
6
- groq β€” Groq (free tier, very fast) β€” llama-3.3-70b-versatile, mixtral-8x7b, etc.
7
- nvidia β€” NVIDIA NIM ($200 free credits) β€” meta/llama-3.3-70b-instruct, etc.
8
- huggingface β€” HuggingFace Inference API (free, rate-limited)
9
- kimi β€” Moonshot AI / Kimi β€” moonshot-v1-8k, moonshot-v1-32k, etc.
10
- openai β€” OpenAI β€” gpt-4o, gpt-4o-mini, etc.
11
- custom β€” Any OpenAI-compatible endpoint (set base_url in config)
12
-
13
- Each agent picks its provider independently, so you can mix and match freely.
 
 
14
  """
15
 
16
  import os
17
  import time
 
18
  from typing import Optional
19
 
20
 
21
- # ── Provider routing ──────────────────────────────────────────────────────────
22
 
23
- # OpenAI-compatible base URLs for known providers.
24
- # These are used when base_url is not explicitly set in config.yaml.
25
  PROVIDER_DEFAULTS = {
26
  "groq": "https://api.groq.com/openai/v1",
27
  "nvidia": "https://integrate.api.nvidia.com/v1",
28
  "huggingface": "https://api-inference.huggingface.co/v1",
29
  "kimi": "https://api.moonshot.cn/v1",
30
- "openai": None, # openai SDK uses its default
31
  "together": "https://api.together.xyz/v1",
32
  "mistral": "https://api.mistral.ai/v1",
33
  }
34
 
35
- # Default env var names per provider (override with api_key_env in config.yaml)
36
  PROVIDER_KEY_ENVS = {
37
  "anthropic": "ANTHROPIC_API_KEY",
38
  "groq": "GROQ_API_KEY",
@@ -45,99 +45,261 @@ PROVIDER_KEY_ENVS = {
45
  "custom": "CUSTOM_API_KEY",
46
  }
47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
 
49
  def _get_api_key(agent_config: dict) -> str:
50
- """Read the API key from the environment."""
51
  provider = agent_config.get("provider", "anthropic")
52
  env_var = agent_config.get("api_key_env") or PROVIDER_KEY_ENVS.get(provider, "API_KEY")
53
  key = os.environ.get(env_var, "")
54
  if not key:
55
  raise EnvironmentError(
56
- f"API key not found. Set the '{env_var}' environment variable "
57
- f"for the '{provider}' provider.\n"
58
- f" export {env_var}='your-key-here'"
59
  )
60
  return key
61
 
62
 
63
- def _call_anthropic(agent_config: dict, user_input: str) -> tuple[str, int, int]:
64
- """Call the Anthropic API. Returns (content, input_tokens, output_tokens)."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
  import anthropic
66
 
67
  key = _get_api_key(agent_config)
68
  client = anthropic.Anthropic(api_key=key)
 
 
 
 
 
 
 
 
 
 
 
 
69
 
70
  response = client.messages.create(
71
- model=agent_config["model"],
72
  max_tokens=agent_config.get("max_tokens", 4096),
73
  temperature=agent_config.get("temperature", 0.7),
74
  system=agent_config["system_prompt"].strip(),
75
- messages=[{"role": "user", "content": user_input}],
76
  )
77
-
78
- content = response.content[0].text
79
- return content, response.usage.input_tokens, response.usage.output_tokens
80
 
81
 
82
- def _call_openai_compat(agent_config: dict, user_input: str) -> tuple[str, int, int]:
83
- """
84
- Call any OpenAI-compatible API (Groq, NVIDIA, HuggingFace, Kimi, OpenAI, custom…).
85
- Returns (content, input_tokens, output_tokens).
86
- """
87
  import openai
88
 
89
  provider = agent_config.get("provider", "openai")
90
  key = _get_api_key(agent_config)
91
-
92
- # Resolve base URL: explicit config overrides provider default
93
  base_url = agent_config.get("base_url") or PROVIDER_DEFAULTS.get(provider)
 
94
 
95
  client = openai.OpenAI(api_key=key, base_url=base_url)
96
 
 
 
 
 
 
 
 
 
97
  response = client.chat.completions.create(
98
- model=agent_config["model"],
99
  max_tokens=agent_config.get("max_tokens", 4096),
100
  temperature=agent_config.get("temperature", 0.7),
101
  messages=[
102
  {"role": "system", "content": agent_config["system_prompt"].strip()},
103
- {"role": "user", "content": user_input},
104
  ],
105
  )
106
-
107
  content = response.choices[0].message.content or ""
108
  usage = response.usage
109
- input_tokens = usage.prompt_tokens if usage else 0
110
- output_tokens = usage.completion_tokens if usage else 0
111
- return content, input_tokens, output_tokens
112
 
113
 
114
  # ── Public API ────────────────────────────────────────────────────────────────
115
 
116
  def run_agent(
117
  agent_config: dict,
118
- model: Optional[str], # global default model (can be overridden per-agent)
119
  user_input: str,
120
  stage: str,
121
  verbose: bool = True,
 
122
  ) -> dict:
123
- """
124
- Run a single agent using the provider specified in agent_config.
125
-
126
- agent_config keys (all from config.yaml):
127
- provider β€” 'anthropic' | 'groq' | 'nvidia' | 'huggingface' | 'kimi' | 'openai' | 'custom'
128
- model β€” model name for this agent (overrides global model)
129
- api_key_env β€” env var name for API key (optional, defaults per provider)
130
- base_url β€” custom API endpoint (optional, for 'custom' provider or overrides)
131
- temperature β€” float 0–1
132
- max_tokens β€” int
133
- system_prompt β€” str
134
- name β€” display name
135
-
136
- Returns a result dict with stage, agent_name, content, token counts, duration.
137
- """
138
  provider = agent_config.get("provider", "anthropic")
139
-
140
- # Per-agent model takes priority over global default
141
  effective_model = agent_config.get("model") or model or "claude-sonnet-4-6"
142
  agent_config = {**agent_config, "model": effective_model}
143
 
@@ -145,23 +307,18 @@ def run_agent(
145
  print(f" β†’ [{provider.upper()}] {agent_config['name']} ({effective_model})...")
146
 
147
  start = time.time()
148
-
149
  try:
150
  if provider == "anthropic":
151
- content, input_tok, output_tok = _call_anthropic(agent_config, user_input)
152
  else:
153
- content, input_tok, output_tok = _call_openai_compat(agent_config, user_input)
154
  except Exception as e:
155
- raise RuntimeError(
156
- f"Agent '{agent_config['name']}' ({provider}) failed: {e}"
157
- ) from e
158
 
159
  duration = round(time.time() - start, 2)
160
-
161
  if verbose:
162
- total_tok = input_tok + output_tok
163
- tok_str = f"{total_tok:,} tokens" if total_tok else "tokens unavailable"
164
- print(f" βœ“ {agent_config['name']} done ({tok_str}, {duration}s)")
165
 
166
  return {
167
  "stage": stage,
@@ -169,7 +326,72 @@ def run_agent(
169
  "provider": provider,
170
  "model": effective_model,
171
  "content": content,
172
- "input_tokens": input_tok,
173
- "output_tokens": output_tok,
174
  "duration_s": duration,
175
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  """
2
+ agents.py β€” Multi-provider agent runner with health checking, fallback, and vision support.
3
+
4
+ Supported providers:
5
+ anthropic β€” Claude (vision-capable)
6
+ groq β€” Groq free tier (text only)
7
+ nvidia β€” NVIDIA NIM ($200 free credits, auto-fallback across models)
8
+ huggingface β€” HuggingFace Inference API
9
+ kimi β€” Moonshot AI / Kimi
10
+ openai β€” OpenAI (vision-capable)
11
+ custom β€” Any OpenAI-compatible endpoint
12
+
13
+ NVIDIA behaviour: on startup a background thread pings all NVIDIA models in parallel.
14
+ When a build runs, run_agent_with_fallback() tries healthy models first and automatically
15
+ falls back to the next model (or to Groq) if any call fails.
16
  """
17
 
18
  import os
19
  import time
20
+ import threading
21
  from typing import Optional
22
 
23
 
24
+ # ── Provider base URLs ────────────────────────────────────────────────────────
25
 
 
 
26
  PROVIDER_DEFAULTS = {
27
  "groq": "https://api.groq.com/openai/v1",
28
  "nvidia": "https://integrate.api.nvidia.com/v1",
29
  "huggingface": "https://api-inference.huggingface.co/v1",
30
  "kimi": "https://api.moonshot.cn/v1",
31
+ "openai": None,
32
  "together": "https://api.together.xyz/v1",
33
  "mistral": "https://api.mistral.ai/v1",
34
  }
35
 
 
36
  PROVIDER_KEY_ENVS = {
37
  "anthropic": "ANTHROPIC_API_KEY",
38
  "groq": "GROQ_API_KEY",
 
45
  "custom": "CUSTOM_API_KEY",
46
  }
47
 
48
+ # ── NVIDIA model priority lists ───────────────────────────────────────────────
49
+
50
+ NVIDIA_TEXT_MODELS = [
51
+ "meta/llama-3.3-70b-instruct",
52
+ "nvidia/llama-3.1-nemotron-70b-instruct",
53
+ "meta/llama-3.1-70b-instruct",
54
+ "mistralai/mixtral-8x7b-instruct-v0.1",
55
+ "microsoft/phi-3-medium-128k-instruct",
56
+ "meta/llama-3.1-8b-instruct",
57
+ ]
58
+
59
+ NVIDIA_CODE_MODELS = [
60
+ "qwen/qwen2.5-coder-32b-instruct",
61
+ "meta/llama-3.3-70b-instruct",
62
+ "nvidia/llama-3.1-nemotron-70b-instruct",
63
+ "mistralai/mixtral-8x7b-instruct-v0.1",
64
+ "meta/llama-3.1-8b-instruct",
65
+ ]
66
+
67
+ NVIDIA_VISION_MODELS = [
68
+ "meta/llama-3.2-90b-vision-instruct",
69
+ "meta/llama-3.2-11b-vision-instruct",
70
+ "microsoft/phi-3-vision-128k-instruct",
71
+ ]
72
+
73
+ # Models that accept image inputs
74
+ VISION_CAPABLE = set(NVIDIA_VISION_MODELS) | {
75
+ "claude-sonnet-4-6", "claude-opus-4-6", "claude-haiku-4-5-20251001",
76
+ "gpt-4o", "gpt-4o-mini", "gpt-4-turbo",
77
+ }
78
+
79
+ # ── Health check state ────────────────────────────────────────────────────────
80
+
81
+ _health: dict[str, bool] = {} # {model_name: is_alive}
82
+ _health_lock = threading.Lock()
83
+ _health_done = False # True once a full check has completed
84
+ _health_in_progress = False
85
+
86
+
87
+ def _ping_model(model: str, api_key: str, base_url: str, results: dict, timeout: int = 12):
88
+ """Worker: ping one model and store True/False in results dict."""
89
+ try:
90
+ import openai
91
+ client = openai.OpenAI(api_key=api_key, base_url=base_url, timeout=timeout)
92
+ client.chat.completions.create(
93
+ model=model,
94
+ messages=[{"role": "user", "content": "Hi"}],
95
+ max_tokens=3,
96
+ )
97
+ results[model] = True
98
+ except Exception:
99
+ results[model] = False
100
+
101
+
102
+ def run_nvidia_health_check(api_key: str = "", force: bool = False) -> dict[str, bool]:
103
+ """
104
+ Ping all NVIDIA models in parallel (up to 20s).
105
+ Returns {model: is_alive}. Results cached for the session; pass force=True to re-check.
106
+ """
107
+ global _health, _health_done, _health_in_progress
108
+
109
+ key = api_key or os.environ.get("NVIDIA_API_KEY", "")
110
+ if not key:
111
+ return {}
112
+
113
+ with _health_lock:
114
+ if _health_done and not force:
115
+ return dict(_health)
116
+ if _health_in_progress:
117
+ return dict(_health)
118
+ _health_in_progress = True
119
+
120
+ all_models = list(dict.fromkeys(
121
+ NVIDIA_TEXT_MODELS + NVIDIA_CODE_MODELS + NVIDIA_VISION_MODELS
122
+ ))
123
+
124
+ results: dict[str, bool] = {}
125
+ threads = [
126
+ threading.Thread(
127
+ target=_ping_model,
128
+ args=(m, key, "https://integrate.api.nvidia.com/v1", results),
129
+ daemon=True,
130
+ )
131
+ for m in all_models
132
+ ]
133
+ for t in threads:
134
+ t.start()
135
+ for t in threads:
136
+ t.join(timeout=22)
137
+
138
+ with _health_lock:
139
+ _health = results
140
+ _health_done = True
141
+ _health_in_progress = False
142
+
143
+ return dict(results)
144
+
145
+
146
+ def reset_health_cache():
147
+ """Clear cached results so the next call re-checks."""
148
+ global _health_done
149
+ with _health_lock:
150
+ _health.clear()
151
+ _health_done = False
152
+
153
+
154
+ def get_health_summary() -> str:
155
+ """Return a markdown table of NVIDIA model health status."""
156
+ with _health_lock:
157
+ if not _health:
158
+ return "*No health check run yet. Click **Check NVIDIA Models** above.*"
159
+ lines = ["| Model | Status |", "|-------|--------|"]
160
+ for model in NVIDIA_TEXT_MODELS + NVIDIA_CODE_MODELS + NVIDIA_VISION_MODELS:
161
+ if model in _health:
162
+ icon = "βœ… Live" if _health[model] else "❌ Down"
163
+ category = (
164
+ "🎨 Vision" if model in NVIDIA_VISION_MODELS
165
+ else "πŸ”¨ Code" if model in NVIDIA_CODE_MODELS
166
+ else "🧠 Text"
167
+ )
168
+ lines.append(f"| `{model}` | {category} Β· {icon} |")
169
+ alive = sum(_health.values())
170
+ lines.append(f"\n**{alive}/{len(_health)} models responding**")
171
+ return "\n".join(lines)
172
+
173
+
174
+ def get_best_nvidia_model(kind: str = "text") -> str:
175
+ """Return the first live NVIDIA model for the given kind (text/code/vision)."""
176
+ candidates = (
177
+ NVIDIA_CODE_MODELS if kind == "code"
178
+ else NVIDIA_VISION_MODELS if kind == "vision"
179
+ else NVIDIA_TEXT_MODELS
180
+ )
181
+ with _health_lock:
182
+ for m in candidates:
183
+ if _health.get(m, True): # assume alive if unchecked
184
+ return m
185
+ return candidates[0]
186
+
187
+
188
+ # ── Internal helpers ──────────────────────────────────────────────────────────
189
 
190
  def _get_api_key(agent_config: dict) -> str:
 
191
  provider = agent_config.get("provider", "anthropic")
192
  env_var = agent_config.get("api_key_env") or PROVIDER_KEY_ENVS.get(provider, "API_KEY")
193
  key = os.environ.get(env_var, "")
194
  if not key:
195
  raise EnvironmentError(
196
+ f"API key not found. Set '{env_var}' for the '{provider}' provider."
 
 
197
  )
198
  return key
199
 
200
 
201
+ def _encode_image(image_input) -> Optional[str]:
202
+ """Convert a PIL Image or numpy array to base64 JPEG. Returns None on failure."""
203
+ if image_input is None:
204
+ return None
205
+ try:
206
+ import io as _io
207
+ import base64 as _b64
208
+ from PIL import Image as PILImage
209
+
210
+ if not isinstance(image_input, PILImage.Image):
211
+ img = PILImage.fromarray(image_input)
212
+ else:
213
+ img = image_input
214
+
215
+ buf = _io.BytesIO()
216
+ img.convert("RGB").save(buf, format="JPEG", quality=90)
217
+ return _b64.b64encode(buf.getvalue()).decode()
218
+ except Exception:
219
+ return None
220
+
221
+
222
+ def _call_anthropic(
223
+ agent_config: dict,
224
+ user_input: str,
225
+ image_b64: Optional[str] = None,
226
+ ) -> tuple[str, int, int]:
227
  import anthropic
228
 
229
  key = _get_api_key(agent_config)
230
  client = anthropic.Anthropic(api_key=key)
231
+ model = agent_config["model"]
232
+
233
+ if image_b64 and model in VISION_CAPABLE:
234
+ content = [
235
+ {
236
+ "type": "image",
237
+ "source": {"type": "base64", "media_type": "image/jpeg", "data": image_b64},
238
+ },
239
+ {"type": "text", "text": user_input},
240
+ ]
241
+ else:
242
+ content = user_input
243
 
244
  response = client.messages.create(
245
+ model=model,
246
  max_tokens=agent_config.get("max_tokens", 4096),
247
  temperature=agent_config.get("temperature", 0.7),
248
  system=agent_config["system_prompt"].strip(),
249
+ messages=[{"role": "user", "content": content}],
250
  )
251
+ text = response.content[0].text
252
+ return text, response.usage.input_tokens, response.usage.output_tokens
 
253
 
254
 
255
+ def _call_openai_compat(
256
+ agent_config: dict,
257
+ user_input: str,
258
+ image_b64: Optional[str] = None,
259
+ ) -> tuple[str, int, int]:
260
  import openai
261
 
262
  provider = agent_config.get("provider", "openai")
263
  key = _get_api_key(agent_config)
 
 
264
  base_url = agent_config.get("base_url") or PROVIDER_DEFAULTS.get(provider)
265
+ model = agent_config["model"]
266
 
267
  client = openai.OpenAI(api_key=key, base_url=base_url)
268
 
269
+ if image_b64 and model in VISION_CAPABLE:
270
+ user_content = [
271
+ {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{image_b64}"}},
272
+ {"type": "text", "text": user_input},
273
+ ]
274
+ else:
275
+ user_content = user_input
276
+
277
  response = client.chat.completions.create(
278
+ model=model,
279
  max_tokens=agent_config.get("max_tokens", 4096),
280
  temperature=agent_config.get("temperature", 0.7),
281
  messages=[
282
  {"role": "system", "content": agent_config["system_prompt"].strip()},
283
+ {"role": "user", "content": user_content},
284
  ],
285
  )
 
286
  content = response.choices[0].message.content or ""
287
  usage = response.usage
288
+ return content, (usage.prompt_tokens if usage else 0), (usage.completion_tokens if usage else 0)
 
 
289
 
290
 
291
  # ── Public API ────────────────────────────────────────────────────────────────
292
 
293
  def run_agent(
294
  agent_config: dict,
295
+ model: Optional[str],
296
  user_input: str,
297
  stage: str,
298
  verbose: bool = True,
299
+ image_b64: Optional[str] = None,
300
  ) -> dict:
301
+ """Run a single agent call. Raises RuntimeError on failure."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
302
  provider = agent_config.get("provider", "anthropic")
 
 
303
  effective_model = agent_config.get("model") or model or "claude-sonnet-4-6"
304
  agent_config = {**agent_config, "model": effective_model}
305
 
 
307
  print(f" β†’ [{provider.upper()}] {agent_config['name']} ({effective_model})...")
308
 
309
  start = time.time()
 
310
  try:
311
  if provider == "anthropic":
312
+ content, in_tok, out_tok = _call_anthropic(agent_config, user_input, image_b64)
313
  else:
314
+ content, in_tok, out_tok = _call_openai_compat(agent_config, user_input, image_b64)
315
  except Exception as e:
316
+ raise RuntimeError(f"Agent '{agent_config['name']}' ({provider}) failed: {e}") from e
 
 
317
 
318
  duration = round(time.time() - start, 2)
 
319
  if verbose:
320
+ total = in_tok + out_tok
321
+ print(f" βœ“ {agent_config['name']} done ({total:,} tokens, {duration}s)")
 
322
 
323
  return {
324
  "stage": stage,
 
326
  "provider": provider,
327
  "model": effective_model,
328
  "content": content,
329
+ "input_tokens": in_tok,
330
+ "output_tokens": out_tok,
331
  "duration_s": duration,
332
  }
333
+
334
+
335
+ def run_agent_with_fallback(
336
+ agent_config: dict,
337
+ user_input: str,
338
+ stage: str,
339
+ image_b64: Optional[str] = None,
340
+ verbose: bool = True,
341
+ ) -> dict:
342
+ """
343
+ Run an agent with automatic NVIDIA model fallback.
344
+
345
+ For non-NVIDIA providers, behaves identically to run_agent().
346
+ For NVIDIA:
347
+ 1. Tries healthy models first (from cached health check).
348
+ 2. On failure, tries the next model in priority order.
349
+ 3. If all NVIDIA models fail, falls back to Groq llama-3.3-70b-versatile.
350
+ 4. If Groq key is absent too, raises a RuntimeError with a clear message.
351
+ """
352
+ provider = agent_config.get("provider", "groq")
353
+
354
+ if provider != "nvidia":
355
+ return run_agent(agent_config, None, user_input, stage, verbose, image_b64)
356
+
357
+ # Pick candidate list based on stage and whether an image is attached
358
+ if image_b64:
359
+ candidates = NVIDIA_VISION_MODELS + (NVIDIA_CODE_MODELS if stage == "builder" else NVIDIA_TEXT_MODELS)
360
+ elif stage == "builder":
361
+ candidates = NVIDIA_CODE_MODELS
362
+ else:
363
+ candidates = NVIDIA_TEXT_MODELS
364
+
365
+ # Sort: healthy first, then unchecked, then known-bad
366
+ with _health_lock:
367
+ healthy = [m for m in candidates if _health.get(m) is True]
368
+ unchecked = [m for m in candidates if m not in _health]
369
+ unhealthy = [m for m in candidates if _health.get(m) is False]
370
+ priority = healthy + unchecked + unhealthy
371
+
372
+ last_err = None
373
+ for model in priority[:5]:
374
+ try:
375
+ cfg = {**agent_config, "model": model}
376
+ result = run_agent(cfg, None, user_input, stage, verbose, image_b64)
377
+ with _health_lock:
378
+ _health[model] = True
379
+ return result
380
+ except Exception as e:
381
+ last_err = e
382
+ with _health_lock:
383
+ _health[model] = False
384
+ if verbose:
385
+ print(f" ⚠ {model} failed ({e}), trying next NVIDIA model...")
386
+ continue
387
+
388
+ groq_key = os.environ.get("GROQ_API_KEY", "")
389
+ if groq_key:
390
+ if verbose:
391
+ print(" ⚠ All NVIDIA models failed. Falling back to Groq llama-3.3-70b-versatile...")
392
+ cfg = {**agent_config, "provider": "groq", "model": "llama-3.3-70b-versatile"}
393
+ return run_agent(cfg, None, user_input, stage, verbose, image_b64)
394
+
395
+ raise RuntimeError(
396
+ f"All NVIDIA models failed and GROQ_API_KEY is not set. Last error: {last_err}"
397
+ )