Spaces:
Sleeping
Sleeping
Download agents.py from sanelyhusen/multi-agent-builder: direct link, hf CLI and curl.
- Browser
- Download file 13.9 kB
-
https://huggingface.co/spaces/sanelyhusen/multi-agent-builder/resolve/main/agents.py
- Command line
-
hf download hf://spaces/sanelyhusen/multi-agent-builder/agents.py
-
curl -L -o agents.py https://huggingface.co/spaces/sanelyhusen/multi-agent-builder/resolve/main/agents.py
13.9 kB
| """ | |
| 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}" | |
| ) | |